Java Example - Multiple Exception Handling (Multiple catch)
Handling of exceptions:
1. When declaring exceptions, it is recommended to declare more specific exceptions so that they can be handled more precisely.
2. Declare as many catch blocks as there are exceptions declared; if the exceptions in multiple catch blocks have an inheritance relationship, the catch block for the parent exception should be placed at the bottom.
The following example demonstrates how to handle multiple exceptions:
ExceptionDemo.java File
class
Demo
{
int
div
(
int
a
,
int
b
)
throws
ArithmeticException
,
ArrayIndexOutOfBoundsException
//
Functionally, the throws keyword is used to declare that this method may encounter problems.
{
int
[
]
arr
=
new
int
[
a
]
;
System
.
out
.
println
(
arr
[
4
]
)
;
//
The first exception created
return
a
/
b
;
//
The second exception created
}
}
class
ExceptionDemo
{
public
static
void
main
(
String
[
]
args
)
//
throws Exception
{
Demo
d
=
new
Demo
(
)
;
try
{
int
x
=
d
.
div
(
4
,
0
)
;
//
The three groups of examples in the program run screenshot correspond to the three lines of code here.
//
int x = d.div(5,0);
//
int x = d.div(4,1);
System
.
out
.
println
(
"
x=
"
x
)
;
}
catch
(
ArithmeticException
e
)
{
System
.
out
.
println
(
e
.
toString
(
)
)
;
}
catch
(
ArrayIndexOutOfBoundsException
e
)
{
System
.
out
.
println
(
e
.
toString
(
)
)
;
}
catch
(
Exception
e
)
//
The parent class is written here to catch any other unexpected exceptions; it can only be placed after the code for the child-class exceptions.
//
However, it is generally not written under normal circumstances.
{
System
.
out
.
println
(
e
.
toString
(
)
)
;
}
System
.
out
.
println
(
"
Over
"
)
;
}
}
The output of the above code is:
java.lang.ArrayIndexOutOfBoundsException: 4
Over
Java Examples