Java Example – Usage of Finally
In Java, the finally keyword is generally used together with try. After the program enters the try block, the code in the finally block is guaranteed to be executed regardless of whether the program terminates due to an exception or returns in some other way.
The following example demonstrates how to use finally to catch an exception (IllegalArgumentException) via e.getMessage():
ExceptionDemo2.java File
public
class
ExceptionDemo2
{
public
static
void
main
(
String
[
]
argv
)
{
new
ExceptionDemo2
(
)
.
doTheWork
(
)
;
}
public
void
doTheWork
(
)
{
Object
o
=
null
;
for
(
int
i
=
0
;
i
<
5
;
i
++
)
{
try
{
o
=
makeObj
(
i
)
;
}
catch
(
IllegalArgumentException
e
)
{
System
.
err
.
println
(
"
Error: (
"
e
.
getMessage
(
)
"
).
"
)
;
return
;
}
finally
{
System
.
err
.
println
(
"
All executed
"
)
;
if
(
o
==
null
)
System
.
exit
(
0
)
;
}
System
.
out
.
println
(
o
)
;
}
}
public
Object
makeObj
(
int
type
)
throws
IllegalArgumentException
{
if
(
type
==
1
)
throw
new
IllegalArgumentException
(
"
is not the specified type:
"
type
)
;
return
new
Object
(
)
;
}
}
The output of the above code is:
都已执行完毕
java.lang.Object@7852e922
Error: (不是指定的类型:1).
都已执行完毕
Java Examples