EXCEPTION HANDLING PROGRAMS IN JAVA
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code....");
}
}
OUTPUT:
Exception in thread main [Link]:/ by zero
rest of the code...
TRY CATCH
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
OUTPUT
[Link]: / by zero
rest of the code
ArrayIndexOutOfBoundsException
public class TryCatchExample8 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// try to handle the ArithmeticException using
ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
mport [Link];
import [Link];
public class TryCatchExample10 {
public static void main(String[] args) {
PrintWriter pw;
try {
pw = new PrintWriter("[Link]"); //may throw exception
[Link]("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
[Link](e);
}
[Link]("File saved successfully");
}
}
OUTPUT
File saved successfully
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
OUTPUT
Arithmetic Exception occurs
rest of the code
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){[Link]("common task completed");}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
[Link]("rest of the code...");
}
}
OUTPUT
Compile-time error
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}
[Link]("normal flow..");
}
}
OUTPUT
C:\Users\Anurati\Desktop\abcDemo>javac [Link]
C:\users\Anurati\Desktop\abcDemo>java NestedTryBlock
going to divide by 0
[Link]: / by zero
[Link]: Index 5 out of bounds for length 5
other statement
normal flow..