You are on page 1of 22

EXCEPTION HANDLING

Exception Handling
• Exception is a runtime error
(OR)
• abnormal condition that arises in code sequence at runtime

• Languages that do not support exception handling,


• errors are handled by using error codes

• JAVA provides an runtime exception handling mechanism

• Exception are fundamental errors that violate rules / Constraints of


JAVA Language
Exception Handling
• JAVA Exception is an object that describes exception condition that
had occurred

• Java Run Time (JRT) creates an object and throws in method that
caused the error

• Thrown Exception is caught and processed in the same method


(OR)
• Can be passed from method in which it had occurred to others
Exception Key Words
• Exception Handling is done using five keywords
(try, catch, throw, throws, finally)

• Program statements monitored for errors are available in try block

• Exception is thrown from try block

• Exception is caught and handled in catch block

• System generated errors are thrown automatically by JRT


Exception Key Words
• Manually Exception can be thrown using throw keyword

• Exception thrown out of a method are specified using throws clause

• Code that had to be executed before method returns must be put


in finally block
Exception Handling Block
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block ends
}
Exception Class Hierarchy
• Throwable class is top of Exception class hierarchy

• Two sub classes for Throwable class they are Exception class
and Error class
Throwable

Exception Error

RuntimeException
• RuntimeException are automatically defined for the programs
• (i.e. Division by zero & Invalid Array indexing)
Errors
• Exception that are not expected under normal circumstances are
Errors

• Errors are used by Java Runtime System to indicate errors in its


enviromnent

• Stack OverFlow is an example of an Error

• Errors cannot be handled in your programs


Uncaught Exception
• Example
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Error Message
java.lang.ArithmeticException: / by zero at
Exc0.main(Exc0.java:4)

• Exception are created by JRT and thrown automatically which is handled by Exc0
• We have not specified any exception handlers and hence default handler used by
JRT
Using try and catch
• Usage of Exception handlers will help fix errors and prevent programs from
automatic termination. Example below
class Exc2 {
public static void main(String args[]) {
int d, a;
try {
d = 0;
a = 42 / d;
} catch (ArithmeticException e) {
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
throw Clause
• Java Runtime uses throw clause to throw exception explicitly

throw ThrowableIntance;

• Throwableinstances are object of Throwable class or its subclass

• Two ways of obtaining a Throwable object


• Using Parameter in catch clause
• Creating object with new operator
throw clause - Example

class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e;
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
Caught inside demoproc.
} Recaught: java.lang.NullPointerException: demo
}
}
throws clause
• Methods not capable of handling specific type of errors

• use throws clause to indicate calling method to handle that kind of


exceptions

Syntax:
type method-name(parameter-list) throws exception-list
{
// body of method
}

• throws are not used with Error and RuntimeException and its
subclasses
throws clause - Example
class ThrowsDemo {
static void throwOne() throws IllegalAccessException{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
finally clause
• finally executes after try or catch block has completed

• finally block will execute whether exception is thrown or not

• finally block will execute whether exception is caught or not

• finally block will be executed before explicit return statement or


method return

• finally clause is optional. try block should have a catch block or


finally clause
finally clause
class FinallyDemo {
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}}}
User-Defined Exception
• User-Defined Exceptions can be created by extending Exception
class

• User-Defined Exceptions can be instantiated /called using throw


clause

• Example:
User Defined Exception
Example
public class MyException extends Exception {

public MyException() {
System.out.println("User Defined Exception");
}
}
class Main {
public static void main(String args[]) {
try {
throw new MyException();
} catch (MyException m) {
System.out.println("Inside Catch Block");
}
}//User Defined Exception
} //Inside Catch Block
Predefined Exception classes
• Predefined exception classes are in the package java.lang

• Most of the classes are subclasses of RuntimeException

• Classes are auto imported and also known as Unchecked exceptions

• Unchecked exceptions are handled automatically

• No methods in JAVA language defines throws clause with


Unchecked exception classes

• Checked exceptions are defined in throws clause of methods


JAVA Built-in Exception (Unchecked)
Exception Meaning

ArithmeticException Arithmetic Errors

ArrayIndexOutOfBoundsException Array index is out of bounds

ArrayStoreException Assignment to array element of an incompatible


array
ClassCastException Invalid Casting

IllegalArgumentException Illegal argument used to invoke method

IndexOutOfBoundsException Some type of index is out of bound

NegativeArraySizeException Array created with a negative size

NullPointerException Invalid use of null reference


JAVA Built-in Exception (Checked)
Thank You

You might also like