try with multiple catch blocks
A way of handling an exception is varied from exception to exception hence, for every exception type, it is highly recommended to take separate catch block.
Let's take two examples of try catch.
Bad Or Worst Programming Practice
try
{
Risky Code
}
catch (Exception e)
{
Exception Handling code
}
Best and Recommended Programming Practice
try
{
Risky Code
}
catch (ArithmeticException e)
{
Perform alternative arithmetic operation
}
catch (SQLException e)
{
USE MYSQL INSTEAD OF ORACLE DB
}
catch (FileNotFoundException e)
{
Use local file instead of remote file
}
catch (Exception e)
{
default handling code here
}
Important LoopHoles:-
- If try with multiple blocks is present in java program then the order is very important. we have to take child exception first then parent exception. Otherwise, we will get Compile Time Error saying "Exception XXX has already has been caught".
class TryWithMultyCatch
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (Exception e)
{
System.out.println(10/2);
}
catch (ArithmeticException e)
{
System.out.println(10/5);
}
}
}class TryWithMultyCatch1
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException e)
{
System.out.println(10/2);
}
catch (Exception e)
{
System.out.println(10/5);
}
}
} - We can't declare two catch block for the same exception otherwise we will get compile time error.
class TryWithMultyCatch1
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException e)
{
System.out.println(10/2);
}
catch (ArithmeticException e)
{
System.out.println(10/2);
}
}
}
No comments:
Post a Comment
Be the first to comment!
Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.
Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
Regards,
JavaByChetan
Back To Home