Unit 6 GTU Exception Handling PDF
Unit 6 GTU Exception Handling PDF
Exception Handling
What is Exception?
• An exception is an unwanted or unexpected
event, which occurs during the execution of a
program i.e at run time, that disrupts the
normal flow of the program’s instructions.
• It is an object which is thrown at runtime.
Exception Handling
• The Exception Handling in Java is one of the
powerful mechanism to handle the runtime
errors so that normal flow of the application
can be maintained.
• Runtime errors such as
ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Error & Exception
• Errors indicate that something severe enough
has gone wrong, the application should crash
rather than try to handle the error.
• Exceptions are events that occurs in the code.
A programmer can handle such conditions and
take necessary corrective actions.
Exception Handling with 5 Keywords
Syntax
Exception Types(Hierarchy)
java.lang.Throwable (Root Class)
ArithmeticException,
IndexOutOfBoundsException,
NullPointerException
1) Checked Exception
• The classes which directly inherit Throwable class
except RuntimeException and Error are known as
checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
• The classes which inherit RuntimeException are known
as unchecked exceptions e.g. ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they
are checked at runtime.
3) Error
• Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Example
Example 2
throw keyword
• throw throwableinstance;
• ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
• Primitive types, such as int or char, as well as
non-Throwable classes, such as String and
Object, cannot be used as exceptions.
• There are two ways you can obtain a
Throwable object:
• using a parameter in a catch clause, or
creating one with the new operator.
example
throws keyword
• throws is a keyword in Java which is used in
the signature of method to indicate that this
method might throw one of the listed type
exceptions
example