Exception Handling
Exception Handling
run time.
• A Java exception is an object that describes an exceptional (that is, error)
• When an exceptional condition arises, an object representing that
exception is created and thrown in the method that caused the error.
• Java exception handling is managed via five keywords: try, catch, throw,
throws, and finally.
• If an exception occurs within the try block, it is thrown. Your code can
catch this exception (using catch) and handle it in some rational manner.
Types of Java Exceptions:
Check Exception:
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
Error
• Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Errors:
Compile Time Error: Syntactical Errors found in the code. It results in
Compile Time Error.
• Detecting Compile Time Errors is Easy ,as Java displays list of errors
along with time in description.
• Call stack is quite useful for debugging, because it pinpoints the precise
sequence of steps that led to the error.
• You will usually want to handle an exception yourself. Doing so
provides two benefits.
• It allows you to fix the error.
• It prevents the program from automatically terminating.
•
• It will cause ArrayIndexOutOfBounds Exception
Nested Try Ststements
• A try statement can be inside the block of another try. Each time a try
statement is entered, the context of that exception is pushed on the
stack.
• To manually throw an exception, use the keyword throw. Any exception that is
thrown out of a method must be specified as such by a throws clause.
• It is possible for your program to throw an exception explicitly, using the throw
statement.
• The general form of throw is shown here:
throw ThrowableInstance;
• ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
• There are two ways you can obtain a Throwable object:
Using a parameter into a catch clause
Creating one with the new operator.
Java’s Built in Exception