JDK 1.7 Features:----
Handling multiple exceptions in a single catch block
package govind;
public
class
MultipleExceptionHandleThroughSingleCatch {
public
static void
main(String[] args) {
int x=0;
int y[]=
{100,200,300,400,500};
try
{
int c=y[5]/x; //line 1
//int c=y[4]/x;
//line 2
}
catch
(ArithmeticException|ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
}
}
o/p:-----------
case :-1
if line 1 is not
commented and line 2 is commented then o/p:-
java.lang.ArrayIndexOutOfBoundsException: 5
at
govind.MultipleExceptionHandleThroughSingleCatch.main(MultipleExceptionHandleThroughSingleCatch.java:12)
case :-2
if line 2 is not
commented and line 1 is commented then o/p:-
java.lang.ArithmeticException: / by zero
at
govind.MultipleExceptionHandleThroughSingleCatch.main(MultipleExceptionHandleThroughSingleCatch.java:13)
==========================================================================
package govind;
public
class
MultipleExceptionHandleThroughSingleCatchError {
public
static void
main(String[] args) {
try
{
int c=10/0;
}
catch(ArithmeticException|RuntimeException
e)
{
e.printStackTrace();
}
}
}
o/p:----------------------
compile time error:------
The exception ArithmeticException is already
caught by the alternative RuntimeException
Exception in thread "main"
java.lang.Error: Unresolved compilation problem:
The
exception ArithmeticException is already caught by the alternative
RuntimeException
at
govind.MultipleExceptionHandleThroughSingleCatchError.main(MultipleExceptionHandleThroughSingleCatchError.java:11)
Note:--------------
Super class exception must be caught
separately (it is a constraint).
So here, in case when your are catching
multiple exceptions,
follow the rule of generalized to more
specialized. It means that, if you are using
super (general) class, don't use child
(specialized) class.
No comments:
Post a Comment