When we are using multiple catch blocks at that time the order of the catches are matter most. It means that all catch blocks must be from most specific one to most general ones. which is sub classes of Exception must come first and then the super classes. If we change the order of the catch block the compiler will give the error of unreachable block. Take a look at the following code snippet.
public class ExceptionTest
{
public static void main(String[] args)
{
try
{
int i = Integer.parseInt("abc"); //This statement throws NumberFormatException
}
catch(Exception ex)
{
System.out.println("This block handles all exception types");
}
catch(NumberFormatException ex)
{
//Compile time error
//This block becomes unreachable as
//exception is already caught by above catch block
}
}
}
No comments:
Post a Comment