Java Exception Handling Programs
Java Exception Handling Programs
}
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3
In this example, we also kept the code in a try
block that will not throw an exception.
public class TryCatchExample3 {
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the
try block, the rest of the block code will not
execute.
Example 4
Here, we handle the exception using the parent
class exception.
TryCatchExample4.java
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
Let's see an example to print a custom message
on exception.
TryCatchExample5.java
Output:
Example 6
Let's see an example to resolve the exception in a
catch block.
TryCatchExample6.java
Output:
25
Example 7
In this example, along with try block, we also
enclose exception code in a catch block.
TryCatchExample7.java
try
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception
}
System.out.println("rest of the code");
}
}
Output:
Example 8
In this example, we handle the generated
exception (Arithmetic Exception) with a different
type of exception class
(ArrayIndexOutOfBoundsException).
TryCatchExample8.java
public class TryCatchExample8 {
}
// try to handle the ArithmeticException
using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
TryCatchExample9.java
java.lang.ArrayIndexOutOfBoundsException: 10
rest of the code
Example 10
Let's see an example to handle checked
exception.
TryCatchExample10.java
import java.io.FileNotFoundException;
import java.io.PrintWriter;
PrintWriter pw;
try {
pw = new PrintWriter("jtp.txt"); //may throw
exception
pw.println("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
System.out.println(e);
}
System.out.println("File saved successfully");
}
}
Test it Now
Output: