Exception - 3
Exception - 3
Exception handling
Throw
Throws
Finally
Chained exception
If a method does not handle a checked exception, the method must declare it using the
throws keyword. The throws keyword appears at the end of a method's signature.
Try to understand the difference between throws and throw keywords, throws is used
to postpone the handling of a checked exception and throw is used to invoke an
exception explicitly.
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo
Recaught: java.lang.NullPointerException: demo
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax −
Example
p ic static oi i St i. g a s( } {
. t a 1 = .e 2 ;
t_ {
s Ste a 3 );
J catch
s Ste
sExce tio. e
. .. {
e ;
Output
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
Chained Exceptions in Java
Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
Throwable(String msg, Throwable cause) :- Where msg is the exception message and
cause is the exception that causes the current exception.
public static void ·n(stri [ args)
try
// sett1 a C ::.on
.i 'tcause( ion(
"'"hi e of t exception"));
ion : h cause.
ion
cept:on
put
���RtE:uepti : E)(Cep'ti
a. ·sis ca e t �ion
User defined exception in java
In java we can create our own exception class and throw that exception using throw
keyword. These exceptions are known as user-defined or custom exceptions.