- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to use catch to handle chained exception in Java
Problem Description
How to use catch to handle chained exception?
Solution
This example shows how to handle chained exception using multiple catch blocks.
public class Main{ public static void main (String args[])throws Exception { int n = 20, result = 0; try { result = n/0; System.out.println("The result is "+result); } catch(ArithmeticException ex) { System.out.println ("Arithmetic exception occoured: "+ex); try { throw new NumberFormatException(); } catch(NumberFormatException ex1) { System.out.println ("Chained exception thrown manually : "+ex1); } } } }
Result
The above code sample will produce the following result.
Arithmetic exception occoured : java.lang.ArithmeticException: / by zero Chained exception thrown manually : java.lang.NumberFormatException
The following is an another example of use catch to handle chained exception in Java
public class Main{ public static void main (String args[])throws Exception { int n = 20,result = 0; try{ result = n/0; System.out.println("The result is"+result); }catch(ArithmeticException ex){ System.out.println("Arithmetic exception occoured: "+ex); try{ int data = 50/0; }catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code..."); } } }
The above code sample will produce the following result.
Arithmetic exception occoured: java.lang.ArithmeticException: / by zero java.lang.ArithmeticException: / by zero rest of the code...
java_exceptions.htm
Advertisements