exception handling in java

18
Exception Handling By :- SURIT DATTA

Upload: surit-datta

Post on 14-Apr-2017

153 views

Category:

Engineering


1 download

TRANSCRIPT

Page 1: Exception Handling in JAVA

Exception Handling

By :- SURIT DATTA

Page 2: Exception Handling in JAVA

Contents What is an Exception ? Error vs. Exception Hierarchy of Java Exception classes Java Exception Handling Keywords Types of Exception in Java Internal working of java try-catch block Exception Handler Java Multi Catch block The Throws / Throw Keywords The finally block Common scenarios where exceptions may occur Sequence of Events for throw Checked Exceptions Un-Checked Exceptions User-defined Exceptions:

Page 3: Exception Handling in JAVA

What is an exception?

Exception is an abnormal condition.

In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is exception handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling.

Page 4: Exception Handling in JAVA

Error vs Exception

Errors: An error represents a condition serious enough that most reasonable applications should not try to catch.

Virtual Machine Error Out of memory Stack overflow Thread Death Linkage Error

Exceptions: An error which reasonable applications should catch.

Array index out of bounds Arithmetic errors (divide by

zero Null Pointer Exception I/O Exceptions

Page 5: Exception Handling in JAVA

Hierarchy of Java Exception classes

Object

Throwable

Exception Error

IOException

SQLException

Runtime Exception

ArithmeticException

NullPointerException

VirtualMachineError

AssertionError

Page 6: Exception Handling in JAVA

Java Exception Handling Keywords There are 5 keywords used in java exception handling.

Try : Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java try block must be followed by either catch or finally block.

Catch : Java catch block is used to handle the Exception. It must be used after the try block only. We can use multiple catch block with a single try.

Finally : Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks.

Throw : You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

Throws : If a method does not handle a checked exception, the method must declare it using the throws keyword. 

Page 7: Exception Handling in JAVA

Types of Exception in Java

ArithmeticExceptionArrayIndexOutOfBoundsExceptionClassCastException IllegalArgumentException IndexOutOfBoundsExceptionNegativeArraySizeExceptionNullPointerExceptionNumberFormatExceptionNoSuchMethodException

Page 8: Exception Handling in JAVA

Internal working of java try-catch block

int data = 10/0; Exception object

An object of exception class is thrown

Is Handled ?YES

NOJVM1.Prints out exception description2.Prints the stack trace3.Terminates the program Rest of code

is executed

Page 9: Exception Handling in JAVA

Exception Handler

Exception "thrown" here

Exception handler

Exception handler

Thrown exception matched against first set of exception handlers

If it fails to match, it is matched against next set of handlers, etc.

If exception matches none of handlers, program is abandoned

Page 10: Exception Handling in JAVA

public class TestMultipleCatchBlock{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");} catch(Exception e){System.out.println("common task completed");} System.out.println("rest of the code..."); } }

At a time only one Exception is occurred and at a time only one catch block is executed.

All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

Java Multi Catch block

Page 11: Exception Handling in JAVA

The Throws / Throw Keywords If a method does not handle a checked exception, the method must declare it using

the throws keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword.

***throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly.***

import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation

throw new RemoteException(); } //Remainder of class definition }

Page 12: Exception Handling in JAVA

The finally block The finally block follows a try block or a catch block. A finally block of code always executes,

irrespective of occurrence of an Exception.

Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.

A finally block appears at the end of the catch blocks and has the following syntax:

try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }finally { //The finally block always executes. }

Page 13: Exception Handling in JAVA

Common scenarios where exceptions may occur ArithmeticException occurs

int a=50/0; //ArithmeticException  

NullPointerException occursString s=null;  System.out.println(s.length()); //NullPointerException 

NumberFormatException occursString s="abc";  int i=Integer.parseInt(s); //NumberFormatException 

ArrayIndexOutOfBoundsException occursint a[]=new int[5];  a[10]=50;  //ArrayIndexOutOfBoundsException

Page 14: Exception Handling in JAVA

Sequence of Events for throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Page 15: Exception Handling in JAVA

Checked Exceptions

Inherit from class Exception but not from RuntimeException

Compiler enforces catch-or-declare requirement

Compiler checks each method call and method declaration

Checked exceptions are checked at compile-time.

e.g. IOException, SQLException etc.

Page 16: Exception Handling in JAVA

Unchecked Exceptions

Inherit from class RuntimeException or class Error

Compiler does not check code to see if exception caught or declared

If an unchecked exception occurs and not caught- Program terminates or runs with unexpected results

Can typically be prevented by proper coding

Page 17: Exception Handling in JAVA

User-defined Exceptions: We can create your own exceptions in Java. Keep the following

points in mind when writing your own exception classes.

All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:class MyException extends Exception{ }

Page 18: Exception Handling in JAVA