You are on page 1of 15

Java Programming

Exception Handling
Exception?
• Short hand for Exceptional Event

• Definition: An exception is an event, which


occurs during the execution of a program, that
disrupts the normal flow of the program's
instructions
Exception - Demo
• ArithmeticException

• NullPointerException

• ArrayIndexOutOfBoundsException
Throwing an Exception
1. Information about the
error
2. Type of the error
3. State of the program when
error occurred

Exception Java Runtime


object Environment
void aMethod()
{ (JRE)
// error occurred
}
What JRE does after an
Exception is thrown?
Where is Exception
Handling code…..? Java
Code

Java Runtime
Environment
(JRE)

The Call Stack


If the type of the exception
object thrown == the type
that can be handled by the
handler
What JRE does if an
then, pass the exception
to the handler
appropriate Exception
Otherwise, terminate JRE
(consequently, the Program) Handler is found?

Java Runtime
Environment
(JRE)

Exception
Searching the call stack for the
object exception handler
What Exception Handler does then?

If Excption Handler found,


then Catch the Exception

Exception
Handler
Types of Exceptions
• Checked Exceptions

• Unchecked Exceptions
Error vs Exception
• Error: An Error indicates serious problem that
a reasonable application should not try to
catch.

• Exception: Exception indicates conditions that


a reasonable application might try to catch.
Advantages of Exceptions
1. Separating Error-Handling Code from
"Regular" Code
2. Propagating Errors Up the Call Stack
3. Grouping and Differentiating Error Types
Simple Exception Handling
• try-catch
Syntax:
try {

}
catch(ExceptionName en) {

}
Exception Handling – Multiple Catch

• try-catch
Syntax:
try {

}
catch(ExceptionName1 en) {

}
catch(ExceptionNameN en) {

}
Exception Handling - finally
• try-catch-finally
Syntax:
try {

}
catch(ExceptionName en) {

}
finally {

You might also like