Advertisement
class TryCatch
{
public static void main(String... ar)
{
int a=10, b=0, c;
try
{
c=a/b; //ArithmeticException i.e. Divide by zero exception is thrown here
System.out.println(c);
}
catch(ArithmeticException ariExp) //matching ArithmeticExcecption is declared in "catch block"
{
System.out.println("We have an Exception - "+ariExp); //message related to caught exception is printed
}
System.out.println("Outside try-catch block");
}
}
We have an Exception - java.lang.ArithmeticException: / by zero
Outside try-catch block
Advertisement
class TryCatch2
{
public static void main(String... ar)
{
TryCatch2 ob = new TryCatch2();
try
{
ob.meth1(); //enclosing the call to meth1() method in try block
}
catch(ArithmeticException e)
{
System.out.println("ArithmaticException thrown by meth1() method is caught in main() method");
}
} //main method ends
public void meth1()
{
try
{
System.out.println(100/0); //ArithmeticException is thrown here
}
catch(NullPointerException nullExp) //Non-matching exception-type is declared in this catch block
{
System.out.println("We have an Exception - "+nullExp);
}
System.out.println("Outside try-catch block");
} //meth1() method ends
}
ArithmeticException thrown by meth1() method is caught in main() method
import java.io.*;
class A
{
public static void main(String... ar)
{
try
{
File f = new File("File.txt");
FileReader fr= new FileReader(f);
}
System.out.println("Statement between try-catch"); //Statement between try-catch block leads to compile error
catch(Exception e)
{
System.out.println(e);
}
}
}
A.java:7: error: 'try' without 'catch', 'finally' or resource declarations
try
^
A.java:13: error: 'catch' without 'try'
catch(Exception e)
^
2 errors
import java.io.*;
class B
{
public static void main(String... ar)
{
try
{
File f = new File("File.txt");
FileReader fr= new FileReader(f);
}
}
B.java:7: error: 'try' without 'catch', 'finally' or resource declarations
try
^
1 error
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement