SlideShare a Scribd company logo
exception handling
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 Exception is a condition caused by a run time error in the program. When the java interpreter identifies an error such as division by 0 it creates an Exception object and throws it Definition:   An  exception  is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Is defined as a condition that interrupts the normal flow of operation within a program.
Exception Handling in Java Java allows Exception handling  mechanism to handle various exceptional conditions. When an exceptional condition occurs, an  exception  is said to be thrown.  For continuing the program execution, the user should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as Exception handling
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 In Java Exception handling is managed by 5 key words: try catch  throw  throws finally
Exception Handling in Java Throwable   Exception   error InterruptedException (checked exception)  RuntimeException (unchecked exception) Exception Hierarchy  Package java.lang
Exception Handling in Java Unchecked exception: These exception need not be included in an method’s  throws  list The compiler does not check to see  if a method handles or throws these exception these are subclasses of  RuntimeException The compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. Class Error and its subclasses also are unchecked. Checked exception:  Must be included in an method’s  throws  list if that method can generate one of those exceptions and does not handle it itself These exception defined by  java.lang
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 getMessage(); All throwable objects can have an associated error message. Calling this message will return the message if one present. getLocalizedMessage(); gets the localized version of error message. printStackTrace(); sends the stack trace to the system console. This is a list of method calls that led to the exception condition. It includes line number and file names too. Printing of the stack trace is the default behavior of a runtime exception when u don’t catch it ourselves. Exception Handling in Java
catch(ArithmeticException e){ System.out.println(e.getMessage()); //e.printStackTrace(); } o/p: E:\JAVAPGMS>java Ex / by zero catch(ArithmeticException e){ e.printStackTrace(); } E:\JAVAPGMS>java Ex o/p: java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:9) 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"); } }
E:\JAVAPGMS>java Ex java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:9) after catch E:\JAVAPGMS>java Ex  20 10 java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:14) after catch E:\JAVAPGMS>java Ex  20 30 5 Array indexjava.lang.ArrayIndexOutOfBoundsException: 10 after catch 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 } } }
E:\JAVAPGMS>java throwDemo -4 java.lang.NegativeArraySizeException: Illegal Array size Exception in thread &quot;main&quot; java.lang.NegativeArraySizeException: Illegal Array size at throwDemo.main(throwDemo.java:17) 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 finally It creates a block of code that will be executed after try/catch block has completed and before the code following try/catch block. It will execute whether or not an exception is thrown finally is useful for: Closing a file Closing a result set Closing the connection established with database This block is optional but when included is placed after the last catch block of a try
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;); } } }
E:\JAVAPGMS>java TestMyException caught my exception too small number from finally O/P: Exception Handling in Java

More Related Content

PPT
Exception handling
PPTX
Exception handling in java
PPTX
Java exception handling
PPTX
Exceptionhandling
PDF
javaexceptions
PPTX
Java Exception Handling and Applets
PPTX
Exception Handling in Java
Exception handling
Exception handling in java
Java exception handling
Exceptionhandling
javaexceptions
Java Exception Handling and Applets
Exception Handling in Java

What's hot (20)

PPT
Exception handling in java
PPTX
Exception handling in java
PPT
Exception handling
PPT
exception handling in java
ODP
Exception Handling In Java
PPTX
Exception handling in java
PPTX
Chap2 exception handling
PPTX
Exception handling in Java
PPTX
7.error management and exception handling
PPTX
Exception handling in java
PPT
Exception handling
PPTX
Java exception handling
PPSX
Exception Handling
PPT
Exception Handling in JAVA
PPT
Java: Exception
PPTX
Exception Handling in Java
PPTX
Exception handling in java
PPT
Java exception
PPT
Exception Handling Java
ODP
Exception handling in java
Exception handling in java
Exception handling in java
Exception handling
exception handling in java
Exception Handling In Java
Exception handling in java
Chap2 exception handling
Exception handling in Java
7.error management and exception handling
Exception handling in java
Exception handling
Java exception handling
Exception Handling
Exception Handling in JAVA
Java: Exception
Exception Handling in Java
Exception handling in java
Java exception
Exception Handling Java
Exception handling in java
Ad

Viewers also liked (20)

PDF
Java exception handling ppt
PPS
Java Exception handling
PPTX
Java - Exception Handling
PPTX
Exception handling in Java
PDF
Exception handling
PPTX
Exceptional Handling in Java
PDF
Java Exception handling
PPT
Applet and graphics programming
PPT
String Handling
PDF
Java Applet and Graphics
PPTX
Chap1 packages
PPT
Packages,interfaces and exceptions
PPTX
Java packages oop
PPT
Java And Multithreading
PPTX
Java packages
PDF
Java - Interfaces & Packages
PDF
27 applet programming
PPT
Java interface
PPTX
Java package
Java exception handling ppt
Java Exception handling
Java - Exception Handling
Exception handling in Java
Exception handling
Exceptional Handling in Java
Java Exception handling
Applet and graphics programming
String Handling
Java Applet and Graphics
Chap1 packages
Packages,interfaces and exceptions
Java packages oop
Java And Multithreading
Java packages
Java - Interfaces & Packages
27 applet programming
Java interface
Java package
Ad

Similar to exception handling (20)

PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPTX
L14 exception handling
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
using Java Exception Handling in Java.pptx
PPT
Chap12
PPTX
Z blue exception
PPT
Exception Handling in java masters of computer application
PPT
9781439035665 ppt ch11
PPTX
Exception Handling.pptx
PPTX
Exception handling
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
L14 exception handling
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Java Exception Handling & IO-Unit-3 (1).ppt
using Java Exception Handling in Java.pptx
Chap12
Z blue exception
Exception Handling in java masters of computer application
9781439035665 ppt ch11
Exception Handling.pptx
Exception handling

Recently uploaded (20)

PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Computing-Curriculum for Schools in Ghana
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Pharma ospi slides which help in ospi learning
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Insiders guide to clinical Medicine.pdf
Renaissance Architecture: A Journey from Faith to Humanism
human mycosis Human fungal infections are called human mycosis..pptx
Computing-Curriculum for Schools in Ghana
2.FourierTransform-ShortQuestionswithAnswers.pdf
Basic Mud Logging Guide for educational purpose
Module 4: Burden of Disease Tutorial Slides S2 2025
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O7-L3 Supply Chain Operations - ICLT Program
STATICS OF THE RIGID BODIES Hibbelers.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Anesthesia in Laparoscopic Surgery in India
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Pharma ospi slides which help in ospi learning
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
GDM (1) (1).pptx small presentation for students
Insiders guide to clinical Medicine.pdf

exception handling

  • 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. Exception Handling in Java Exception is a condition caused by a run time error in the program. When the java interpreter identifies an error such as division by 0 it creates an Exception object and throws it Definition:  An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Is defined as a condition that interrupts the normal flow of operation within a program.
  • 5. Exception Handling in Java Java allows Exception handling mechanism to handle various exceptional conditions. When an exceptional condition occurs, an exception is said to be thrown. For continuing the program execution, the user should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as Exception handling
  • 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. Exception Handling in Java In Java Exception handling is managed by 5 key words: try catch throw throws finally
  • 8. Exception Handling in Java Throwable Exception error InterruptedException (checked exception) RuntimeException (unchecked exception) Exception Hierarchy Package java.lang
  • 9. Exception Handling in Java Unchecked exception: These exception need not be included in an method’s throws list The compiler does not check to see if a method handles or throws these exception these are subclasses of RuntimeException The compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. Class Error and its subclasses also are unchecked. Checked exception: Must be included in an method’s throws list if that method can generate one of those exceptions and does not handle it itself These exception defined by java.lang
  • 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. Common Throwable methods getMessage(); All throwable objects can have an associated error message. Calling this message will return the message if one present. getLocalizedMessage(); gets the localized version of error message. printStackTrace(); sends the stack trace to the system console. This is a list of method calls that led to the exception condition. It includes line number and file names too. Printing of the stack trace is the default behavior of a runtime exception when u don’t catch it ourselves. Exception Handling in Java
  • 19. catch(ArithmeticException e){ System.out.println(e.getMessage()); //e.printStackTrace(); } o/p: E:\JAVAPGMS>java Ex / by zero catch(ArithmeticException e){ e.printStackTrace(); } E:\JAVAPGMS>java Ex o/p: java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:9) Use of getMessage() and printStackTrace() Exception Handling in Java
  • 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. E:\JAVAPGMS>java Ex java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:9) after catch E:\JAVAPGMS>java Ex 20 10 java.lang.ArithmeticException: / by zero at Ex.main(Ex.java:14) after catch E:\JAVAPGMS>java Ex 20 30 5 Array indexjava.lang.ArrayIndexOutOfBoundsException: 10 after catch Exception Handling in Java
  • 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. E:\JAVAPGMS>java throwDemo -4 java.lang.NegativeArraySizeException: Illegal Array size Exception in thread &quot;main&quot; java.lang.NegativeArraySizeException: Illegal Array size at throwDemo.main(throwDemo.java:17) Exception Handling in Java
  • 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. Exception Handling in Java finally It creates a block of code that will be executed after try/catch block has completed and before the code following try/catch block. It will execute whether or not an exception is thrown finally is useful for: Closing a file Closing a result set Closing the connection established with database This block is optional but when included is placed after the last catch block of a try
  • 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. E:\JAVAPGMS>java TestMyException caught my exception too small number from finally O/P: Exception Handling in Java