SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Exception Handling in Java Types of Errors 1.Compile time All syntax errors identified by java compiler. No class file is created when this occurs. So it is necessary to fix all compile time errors  for successful compilation. Egs: Missing of semicolon, use of = instead of ==
Exception Handling in Java 2.Run time Some pgms may not run successfully due to wrong logic or errors like stack overflow. Some of the Common run time errors are: Division by 0 Array index out of bounds Negative array size etc..
Exception Handling in Java ,[object Object],[object Object],[object Object],[object Object]
Exception Handling in Java ,[object Object],[object Object]
Exception Handling in Java This mechanism consists of : 1.  Find the problem(Hit the Exception) 2.  Inform that an error has occurred(Throw the  Exception) 3.  Receive the error Information(Catch the  Exception) 4.  Take corrective actions(Handle the Exception)
Exception Handling in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exception Handling in Java Throwable   Exception   error InterruptedException (checked exception)  RuntimeException (unchecked exception) Exception Hierarchy  Package java.lang
Exception Handling in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exception Handling in Java Java’s unchecked  RuntimeException  subclasses defined in  java.lang Exception Meaning  ArithmeticException  Arithmetic error, such as divide-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds ArrayStoreException Assignment to an array element of an incompatible type ClassCastException Invalid cast EnumConstantNotPresentException An attempt is made to use an undefined enumeration value IllegalArgumentException Illegal argument used to invoke a method IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state IndexOutOfBoundsException Some type of index is out-of-bounds NegativeArraySizeException Array created with a negative size
Exception Handling in Java Exception Meaning  NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format SecurityException Attempt to violate security StringIndexOutOfBoundsException Attempt to index outside the bounds of a string TypeNotPresentException Type not fount UnsupportedOperationException An unsupported operation  was encountered
Exception Handling in Java Java’s checked Exception   defined in  java.lang Exception Meaning  ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the  Cloneable  interface IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread NoSuchFieldException A requested field does not exist NoSuchMethodException A requested method does not exist
Exception Handling in Java class Ex{ public static void main(String args[]){  int a=0; int b=2/a; } } Java.lang.ArithmeticException: / by zero at Ex.main
Exception Handling in Java try & catch try Block Statement that causes Exception Catch Block Statement that causes Exception
Exception Handling in Java try { Statement: } catch (Exception-type e){ statement; }
Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a; try{   d=0; a=10/d; System.out.println("from try"); }catch(ArithmeticException e) { System.out.println("divsn by Zero"); } System.out.println("after catch"); } } Once an exception is thrown , program control transfers out of the try block into the catch block. Once the catch statement is executed pgm control continues with the next line following the entire try/catch mechanism.
Exception Handling in Java We can display the description  of an Exception in a println statement by simply passing the exception as an argument. catch(ArithmeticException ae){ System.out.println(“Exception:”+ae); } o/p Exception:java.lang.ArithmeticException: /by zero
Common Throwable methods ,[object Object],[object Object],[object Object],Exception Handling in Java
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Use of getMessage() and printStackTrace() Exception Handling in Java
Exception Handling in Java Multiple catch Statement some cases, more than one exception could be raised by a single piece of code.  such cases we can specify two or more catch clauses, each catching a different type of exception.  when an exception thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed.  After 1 catch statement is executed, the others are bypassed and execution continues after the try/catch block.
Exception Handling in Java class Ex{ public static void main(String  args[]){ int d,a,len; try{   len=args.length; a=10/len; int c[]={1}; c[10]=23; } catch(ArithmeticException e){ System.out.println("divsn by  Zero"+e); } catch(ArrayIndexOutOfBoundsExcept ion ae){ System.out.println("Array index"+ae); } System.out.println("after catch"); } }
Exception Handling in Java In multiple catch statement exception subclasses must come before any of their superclasses. Because a catch statement that uses a superclass will catch exception of that type plus any of its subclasses. Thus  a subclass would never be reached if it came after its superclass. Further  java compiler produces an error unreachable code.
Exception Handling in Java Nested try statement try statement can be nested class Ex{ public static void main(String dd[]){ int d,a,len; try{ len=dd.length; a=10/len; System.out.println(a); try{   if(len==1) len=len/(len-len); if(len==2){   int c[]={1}; c[10]=23; } } catch(ArrayIndexOutOfBoundsExceptio  n ae){ System.out.println("Array index"+ae); } } catch(ArithmeticException e){ e.printStackTrace(); } } System.out.println("after catch"); } }
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Exception Handling in Java
Exception Handling in Java throw It is possible to throw an exception explicitly. Syntax: throw  ThrowableInstance throwableInstance  must b an object of type Throwable or a subclass of Throwable. By two ways we can obtain a Throwable object 1. Using parameter into a catch clause 2. Creating one with new operator
Exception Handling in Java class throwDemo{ public static void main(String args[]){ int size; int arry[]=new int[3]; size=Integer.parseInt(args[0]); try{ if(size<=0)throw new NegativeArraySizeException(&quot;Illegal  Array size&quot;); for(int i=0;i<3;i++) arry[i]+=i+1; }catch(NegativeArraySizeException e){ System.out.println(e); throw e;  //rethrow the exception } } }
[object Object],[object Object],[object Object],[object Object],Exception Handling in Java
Exception Handling in Java throws If a method causing an exception that it doesn't handle, it must specify this behavior that callers of the method can protect themselves against the exception. This can be done by using throws clause. throws clause lists the types of exception that a method might throw. Form type methodname(parameter list) throws Exception list {//body of method}
Exception Handling in Java import java.io.*; class ThrowsDemo{ public static void main(String args[]) throws  IOException,NumberFormatException{ int i; InputStreamReader is=new  InputStreamReader(System.in); BufferedReader br=new BufferedReader(in); i=Integer.parseInt(br.readLine()); System.out.println (i); }}
Exception Handling in Java ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exception Handling in Java Form: try {} catch(exceptiontype e) {} finally {} finally finally Catch block try block
Exception Handling in Java Creating our own Exception class For creating an exception class our own simply make  our class as subclass of the super class Exception. Eg: class  MyException  extends  Exception { MyException (String msg){ super(msg); } }
Exception Handling in Java class TestMyException{ public static void main(String args[]){ int x=5,y=1000; try{ float z=(float)x/(float)y; if(z<0.01){   throw new MyException(&quot;too small number&quot;); } }catch(MyException me){ System.out.println(&quot;caught my exception&quot;); System.out.println(me.getMessage()); } finally{ System.out.println(&quot;from finally&quot;); } } }
[object Object],[object Object],[object Object],[object Object],O/P: Exception Handling in Java

Weitere ähnliche Inhalte

Was ist angesagt?

Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAdil Mehmoood
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 

Was ist angesagt? (20)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling
Exception handling Exception handling
Exception handling
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception
Java exception Java exception
Java exception
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Andere mochten auch

Andere mochten auch (20)

Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
String Handling
String HandlingString Handling
String Handling
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Java Applet
Java AppletJava Applet
Java Applet
 
Chap1 packages
Chap1 packagesChap1 packages
Chap1 packages
 
Packages,interfaces and exceptions
Packages,interfaces and exceptionsPackages,interfaces and exceptions
Packages,interfaces and exceptions
 
Java packages oop
Java packages oopJava packages oop
Java packages oop
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Java packages
Java packagesJava packages
Java packages
 
Java - Interfaces & Packages
Java - Interfaces & PackagesJava - Interfaces & Packages
Java - Interfaces & Packages
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 
Java interface
Java interfaceJava interface
Java interface
 
Java package
Java packageJava package
Java package
 

Ähnlich wie Exception Handling in Java Types and Mechanisms

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 

Ähnlich wie Exception Handling in Java Types and Mechanisms (20)

UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exeption handling
Exeption handlingExeption handling
Exeption handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling
Exception handlingException handling
Exception handling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 

Kürzlich hochgeladen

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Kürzlich hochgeladen (20)

Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

Exception Handling in Java Types and Mechanisms

  • 1.
  • 2. Exception Handling in Java Types of Errors 1.Compile time All syntax errors identified by java compiler. No class file is created when this occurs. So it is necessary to fix all compile time errors for successful compilation. Egs: Missing of semicolon, use of = instead of ==
  • 3. Exception Handling in Java 2.Run time Some pgms may not run successfully due to wrong logic or errors like stack overflow. Some of the Common run time errors are: Division by 0 Array index out of bounds Negative array size etc..
  • 4.
  • 5.
  • 6. Exception Handling in Java This mechanism consists of : 1. Find the problem(Hit the Exception) 2. Inform that an error has occurred(Throw the Exception) 3. Receive the error Information(Catch the Exception) 4. Take corrective actions(Handle the Exception)
  • 7.
  • 8. Exception Handling in Java Throwable Exception error InterruptedException (checked exception) RuntimeException (unchecked exception) Exception Hierarchy Package java.lang
  • 9.
  • 10. Exception Handling in Java Java’s unchecked RuntimeException subclasses defined in java.lang Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds ArrayStoreException Assignment to an array element of an incompatible type ClassCastException Invalid cast EnumConstantNotPresentException An attempt is made to use an undefined enumeration value IllegalArgumentException Illegal argument used to invoke a method IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state IndexOutOfBoundsException Some type of index is out-of-bounds NegativeArraySizeException Array created with a negative size
  • 11. Exception Handling in Java Exception Meaning NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format SecurityException Attempt to violate security StringIndexOutOfBoundsException Attempt to index outside the bounds of a string TypeNotPresentException Type not fount UnsupportedOperationException An unsupported operation was encountered
  • 12. Exception Handling in Java Java’s checked Exception defined in java.lang Exception Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread NoSuchFieldException A requested field does not exist NoSuchMethodException A requested method does not exist
  • 13. Exception Handling in Java class Ex{ public static void main(String args[]){ int a=0; int b=2/a; } } Java.lang.ArithmeticException: / by zero at Ex.main
  • 14. Exception Handling in Java try & catch try Block Statement that causes Exception Catch Block Statement that causes Exception
  • 15. Exception Handling in Java try { Statement: } catch (Exception-type e){ statement; }
  • 16. Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a; try{ d=0; a=10/d; System.out.println(&quot;from try&quot;); }catch(ArithmeticException e) { System.out.println(&quot;divsn by Zero&quot;); } System.out.println(&quot;after catch&quot;); } } Once an exception is thrown , program control transfers out of the try block into the catch block. Once the catch statement is executed pgm control continues with the next line following the entire try/catch mechanism.
  • 17. Exception Handling in Java We can display the description of an Exception in a println statement by simply passing the exception as an argument. catch(ArithmeticException ae){ System.out.println(“Exception:”+ae); } o/p Exception:java.lang.ArithmeticException: /by zero
  • 18.
  • 19.
  • 20. Exception Handling in Java Multiple catch Statement some cases, more than one exception could be raised by a single piece of code. such cases we can specify two or more catch clauses, each catching a different type of exception. when an exception thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After 1 catch statement is executed, the others are bypassed and execution continues after the try/catch block.
  • 21. Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a,len; try{ len=args.length; a=10/len; int c[]={1}; c[10]=23; } catch(ArithmeticException e){ System.out.println(&quot;divsn by Zero&quot;+e); } catch(ArrayIndexOutOfBoundsExcept ion ae){ System.out.println(&quot;Array index&quot;+ae); } System.out.println(&quot;after catch&quot;); } }
  • 22. Exception Handling in Java In multiple catch statement exception subclasses must come before any of their superclasses. Because a catch statement that uses a superclass will catch exception of that type plus any of its subclasses. Thus a subclass would never be reached if it came after its superclass. Further java compiler produces an error unreachable code.
  • 23. Exception Handling in Java Nested try statement try statement can be nested class Ex{ public static void main(String dd[]){ int d,a,len; try{ len=dd.length; a=10/len; System.out.println(a); try{ if(len==1) len=len/(len-len); if(len==2){ int c[]={1}; c[10]=23; } } catch(ArrayIndexOutOfBoundsExceptio n ae){ System.out.println(&quot;Array index&quot;+ae); } } catch(ArithmeticException e){ e.printStackTrace(); } } System.out.println(&quot;after catch&quot;); } }
  • 24.
  • 25. Exception Handling in Java throw It is possible to throw an exception explicitly. Syntax: throw ThrowableInstance throwableInstance must b an object of type Throwable or a subclass of Throwable. By two ways we can obtain a Throwable object 1. Using parameter into a catch clause 2. Creating one with new operator
  • 26. Exception Handling in Java class throwDemo{ public static void main(String args[]){ int size; int arry[]=new int[3]; size=Integer.parseInt(args[0]); try{ if(size<=0)throw new NegativeArraySizeException(&quot;Illegal Array size&quot;); for(int i=0;i<3;i++) arry[i]+=i+1; }catch(NegativeArraySizeException e){ System.out.println(e); throw e; //rethrow the exception } } }
  • 27.
  • 28. Exception Handling in Java throws If a method causing an exception that it doesn't handle, it must specify this behavior that callers of the method can protect themselves against the exception. This can be done by using throws clause. throws clause lists the types of exception that a method might throw. Form type methodname(parameter list) throws Exception list {//body of method}
  • 29. Exception Handling in Java import java.io.*; class ThrowsDemo{ public static void main(String args[]) throws IOException,NumberFormatException{ int i; InputStreamReader is=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(in); i=Integer.parseInt(br.readLine()); System.out.println (i); }}
  • 30.
  • 31. Exception Handling in Java Form: try {} catch(exceptiontype e) {} finally {} finally finally Catch block try block
  • 32. Exception Handling in Java Creating our own Exception class For creating an exception class our own simply make our class as subclass of the super class Exception. Eg: class MyException extends Exception { MyException (String msg){ super(msg); } }
  • 33. Exception Handling in Java class TestMyException{ public static void main(String args[]){ int x=5,y=1000; try{ float z=(float)x/(float)y; if(z<0.01){ throw new MyException(&quot;too small number&quot;); } }catch(MyException me){ System.out.println(&quot;caught my exception&quot;); System.out.println(me.getMessage()); } finally{ System.out.println(&quot;from finally&quot;); } } }
  • 34.