exception handling
DESCRIPTION
Description about Exception HandlingTRANSCRIPT
Exception Handling
Presentation on
Presented By :Sumit Lole
1
Agenda
2
What is Exception?
Exception Hierarchy
Exception vs. Error
Types of Exception
Default Exception Handler
Exception Handling
Creating Your own Exception
Exception
Definition:
“An exception is an event, which occurs during
the execution of a program, that disrupts the
normal flow of the program's instructions”
An exception occurs when our code asks the
JVM to perform the technically impossible and
unanticipated (by the compiler)!
3
Exception Hierarchy
All exception types are subclasses of the built-in class Throwable
Throwable has two subclasses :
Exception
Error
4
Throwable
Error Exception
RuntimeException
IOExceptionThe Java
Exception Hierarchy
5
Error
Error hierarchy describes internal errors
and resource exhaustion.
Don’t throw an object of this type!
Relatively rare
Mostly beyond programmers control
6
Types of Exceptions in Java
Checked exceptions
All exception inherited from Exception
Class
Unchecked exceptions
All exception inherited from
RuntimeException Class
7
8
Default Exception Handler ?
Default handler prints a stack trace from
the point at which the exception occurred,
and terminates the program
Example: BasicDemo.java9
Exception Handling
1. Anticipate the error by the user/system.
2. Return the program to a safe state that
enables the user to execute other
commands.
3. Inform the user of the error’s cause.
4. Allow the user to save work and terminate
the program gracefully.
10
Ways to throw an Exception
1. Calling a method that throws a checked
exception
2. Code detects an error and generates checked
exception with throw statement
3. Programming error e.g. a[-1] =0; generates
an unchecked exception
ArrayIndexOutOfBoundsException
4. JVM or runtime library internal error
11
Keywords for Java Exceptions
throws
throw
try
catch
finally
12
Catching Exceptions
“What goes up must come down”
Catching exceptions is a bit trickier
An uncaught exception will terminate
the program …
… print the exception type to screen …
… print the stack trace.
13
Using try and catch
14
Placed the code (which is suppose to throw an
exception) inside a block of code starting with the
“try” keyword
The catch clause should follow immediately the
try block.
Once the catch statement has executed, program
control continues with the next line in the program
following the entire try/catch mechanism
Example : InitialDemo.java
Nested Try StatementA 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
If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match
If a method call within a try block has try block within it, then then it is still nested try
Example : ExceptionChaining.java
15
What information does java.lang.Exception contain The type of exception -- the exception class
Where the exception occurred -- the stack
trace
Context and explanatory information --
the error message, and other state information
Example : StackTrace.java
16
finallyIt is used to handle premature execution of a
method (i.e. a method open a file upon entry and
closes it upon exit)
finally creates a block of code that will be
executed after try/catch block has completed
and before the code following the try/catch block
finally clause will execute whether or not an
exception is thrown
17
Some Important Exception that generally occurs…IOExceptionClassNotFoundExceptionRuntimeException
Most occurring exceptionCaused by programming error“If it’s a RuntimeException it’s your
fault!”Example :
ArrayIndexOutOfBoundExceptionIndexOutOfBoundArithmeticExceptionNullPointerException
Example : ExceptionExample.java18
throwIt is possible for your program to throw
an exception explicitlythrow ExceptionInstance
Here, ExceptionInstance must be an object of type Throwable or a subclass Throwable
There are two ways to obtain a Throwable objects:Using a parameter into a catch clauseCreating one with the new operator
19
Creating Your Own ExceptionsJava provides over 40 categories of Exceptions
Java allows you to create your own ExceptionsExtend a subclass of Throwable
Exception class constructorsException()Exception(String message)Exception(String message, Throwable cause)
Exception(Throwable cause)
20
Example
21
throw statement : throw <object reference expression>;
Class DivisionByZeroException extends Exception{DivisionByZeroException(String msg) {
super(msg);}
}public void division(){
int num1 = 10;int num2 = 0;if(num2 == 0)
throw new DivisionByZeroException();System.out.println(num1/num2);
}
throwsIf a method is capable of causing an exception
that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exceptiontype method-name parameter-list) throws exception-
list{
// body of method}
It is not applicable for Error or RuntimeException, or any of their subclasses
22
Rule for Method Overriding
23
While overriding, the new method definition in the subclass can only specify all or a subset of the exception classes specified in the throws clause of the overridden method in the superclass
Some Methods Inherited from Throwable
24
fillStackTrace() returns ThrowablegetCause() returns ThrowablegetMessage() returns StringgetStackTrace() return
StackTraceElement[] - ThrowableinitCause(Throwable) printSatckTrace() return voidsetStackTrace(Throwable) toString() return String
Queries
25
26