EXCEPTIONS HANDLING
EXCEPTIONS HANDLING
An exception is an abnormal condition that arises in a code sequence at run time.
In other words, an e...
SCENARIO
Imagine you’re about to board an airplane to Geneva to attend an important
conference.
At the last minute, you le...
TYPES OF EXCEPTION
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked ...
TYPES OF EXCEPTION
2)UnChecked Exception
3)Error
The classes that extend RuntimeException are known as unchecked exception...
EXCEPTION HIERARCHY
 All exception classes are subtypes of the java.lang.Exception
class.
Throwable
Error Exception
IOExc...
Runtime (Checked Exception)
 Checked exceptions are subject to the Catch or Specify
Requirement
 All exceptions are chec...
SCENARIOS WHERE EXCEPTION MAY OCCUR
 If we divide any number by zero, there occurs an ArithmeticException.
 If we have n...
Code without Exception Handling
 A method catches an exception using a combination of
the try and catch keywords. If we d...
HOW EXCEPTION HANDLING OCCURS
 Yes No
a[3]
exception object
Is handled?
JVM
Prints Exception Description
Print stacktrace...
Catching Exception
 A method catches an exception using a combination of
the try and catch keywords. A try/catch block is...
Multiple catch blocks
try
{
//Protected code
}catch(Exception1 e1)
{
//Catch block
}catch(Exception2 e2)
{
//Catch block
}...
At a time only one Exception is
occured and at a time only
one catch block is executed.
EXAMPLE OF MULTICATCH
 Result
cla...
MULTICATCH EXAMPLE 2 All catch blocks must be ordered from most specific to most general i.e. catch
for ArithmeticExcepti...
NESTED TRY BLOCK
public class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divid...
finally Block
Yes
NO Yes No
Program Code
Exception
Occurred
Exception
Handled
Finally Block Executes
finally must be
follo...
throw KEYWORD
 The throw keyword is used to explictily throw an exception.
class Excep13{
static void verify (int age){
i...
THROWING OWN USERDEFINED EXCEPTIONS
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
...
throws KEYWORD
 If you are calling a method that declares an exception, you
must either catch or declare the exception.
i...
CASE1: YOU HANDLE THE EXCEPTION
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device ...
CASE2: YOU DECLARE THE EXCEPTION

import java.io.*;
class M{
void method()throws IOException{
System.out.println("device ...
DIFFERENCE BETWEEN THROW AND THROWS:
1. throw is used to
explicitly throw an
exception.
2. checked exception
can not be
pr...
Upcoming SlideShare
Loading in...5
×

16-Exceptions Handling java

128

Published on

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
128
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
11
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

16-Exceptions Handling java

  1. 1. EXCEPTIONS HANDLING
  2. 2. EXCEPTIONS HANDLING An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. Java’s exception handling, brings run-time error management into the object oriented world. Exception-Handling Fundamentals A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. 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.
  3. 3. SCENARIO Imagine you’re about to board an airplane to Geneva to attend an important conference. At the last minute, you learn that the flight has been cancelled because the pilot isn’t feeling well. Fortunately, the airline quickly arranges for an alternative pilot, allowing the flight to take off at its originally scheduled time. What a relief. This example illustrates how exceptional conditions can modify the initial flow of an action and demonstrates the need to handle those conditions appropriately. In Java, an exceptional condition (like the illness of a pilot) can affect the normal code flow (airline flight operation). In this context, the arrangement for an alternative pilot can be compared to an exception handler. Depending on the nature of the exceptional condition, you may or may not be able to recover completely. For example, would airline management have been able to get your flight off the ground if instead an earthquake had damaged much of the airport?
  4. 4. TYPES OF EXCEPTION There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. 1.Checked Exception 2.Unchecked Exception 3.Error 1)Checked Exception The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
  5. 5. TYPES OF EXCEPTION 2)UnChecked Exception 3)Error The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
  6. 6. EXCEPTION HIERARCHY  All exception classes are subtypes of the java.lang.Exception class. Throwable Error Exception IOException(CHECKED) RuntimeException(UNCHECKED) Object
  7. 7. Runtime (Checked Exception)  Checked exceptions are subject to the Catch or Specify Requirement  All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.  The second kind of exception is the error.  These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
  8. 8. SCENARIOS WHERE EXCEPTION MAY OCCUR  If we divide any number by zero, there occurs an ArithmeticException.  If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.  The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException  If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below: int a=50/0;//ArithmeticException String s=null; System.out.println(s.length());//NullPointerException String s="abc"; int i=Integer.parseInt(s);//NumberFormatException int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  9. 9. Code without Exception Handling  A method catches an exception using a combination of the try and catch keywords. If we donot catch thrown Exception, an abnormal condition occurs and execution stops.   Result public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); System.out.println("Out of the block"); } } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at ExcepTest.main(ExcepTest.java:4)
  10. 10. HOW EXCEPTION HANDLING OCCURS  Yes No a[3] exception object Is handled? JVM Prints Exception Description Print stacktrace Terminates program Rest of the code is Executed
  11. 11. Catching Exception  A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception, if we catch exception thrown the remaining code will also excute.  Result import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
  12. 12. Multiple catch blocks try { //Protected code }catch(Exception1 e1) { //Catch block }catch(Exception2 e2) { //Catch block }catch(Exception3 e3) { //Catch block } try { //Protected code }catch(Exception1 | Exception2 | Exception2 e1){ //Catch block } InJDK1.7
  13. 13. At a time only one Exception is occured and at a time only one catch block is executed. EXAMPLE OF MULTICATCH  Result class Excep4{ 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..."); } } task1 completed rest of the code...
  14. 14. MULTICATCH EXAMPLE 2 All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .  Output:Compile-time error: ArithmeticException already been caught class Excep4{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){System.out.println("common task completed");} catch(ArithmeticException e){System.out.println("task1 is completed");} catch(ArrayIndexOutOfBoundsException e) {System.out.println("task 2 completed");} System.out.println("rest of the code..."); } }
  15. 15. NESTED TRY BLOCK public class Excep6{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println("other statement"); }catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } }
  16. 16. finally Block Yes NO Yes No Program Code Exception Occurred Exception Handled Finally Block Executes finally must be followed by try or catch block. For each try block there can be zero or more catch blocks, but only one finally block. Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
  17. 17. throw KEYWORD  The throw keyword is used to explictily throw an exception. class Excep13{ static void verify (int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ verify(13); System.out.println("rest of the code..."); } } Output:Exception in thread main java.lang.ArithmeticException:not valid
  18. 18. THROWING OWN USERDEFINED EXCEPTIONS class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class Excep13{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } } Output:Exception occured: InvalidAgeException:not valid rest of the code...
  19. 19. throws KEYWORD  If you are calling a method that declares an exception, you must either catch or declare the exception. import java.io.IOException; class Simple{ void m()throws IOException{ throw new IOException("device error");//checked exception } void n()throws IOException{ m(); } void p(){ try{ n(); }catch(Exception e){System.out.println("exception handled"); }} public static void main(String args[]){ Simple obj=new Simple(); obj.p(); System.out.println("normal flow..."); } }
  20. 20. CASE1: YOU HANDLE THE EXCEPTION import java.io.*; class M{ void method()throws IOException{ throw new IOException("device error"); } } class Test{ public static void main(String args[]){ try{ M ob=new M(); ob.method(); }catch(Exception e){System.out.println("exception handled");} System.out.println("normal flow..."); } } i = Output:exception handled normal flow...
  21. 21. CASE2: YOU DECLARE THE EXCEPTION  import java.io.*; class M{ void method()throws IOException{ System.out.println("device operation performed"); } } class Test{ public static void main(String args[])throws IOException{//declare exception M ob=new M(); ob.method(); System.out.println("normal flow..."); } } Output:device operation performed normal flow...
  22. 22. DIFFERENCE BETWEEN THROW AND THROWS: 1. throw is used to explicitly throw an exception. 2. checked exception can not be propagated without throw. 3. throw is followed by an instance. 4. throw is used within the method. 5. You cannot throw multiple exception 1. throws is used to declare an exception. 2. checked exception can be propagated with throws. 3. throws is followed by class. 4. throws is used with the method signature. 5. You can declare multiple exception e.g. public void method()throws IOException,SQLExceptio n.
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×