0% found this document useful (0 votes)
37 views22 pages

Lecture 17 Exception Handling

This document provides an overview of exception handling in Java. It discusses key concepts like try/catch blocks, throws clauses, and the hierarchy of Java exception classes. The try block is used to enclose code that might throw an exception. It must be followed by a catch or finally block. The catch block handles any exceptions, while finally ensures code is always executed. Methods use throws clauses to declare exceptions they might throw but do not handle themselves.

Uploaded by

Kashif Mujeeb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
37 views22 pages

Lecture 17 Exception Handling

This document provides an overview of exception handling in Java. It discusses key concepts like try/catch blocks, throws clauses, and the hierarchy of Java exception classes. The try block is used to enclose code that might throw an exception. It must be followed by a catch or finally block. The catch block handles any exceptions, while finally ensures code is always executed. Methods use throws clauses to declare exceptions they might throw but do not handle themselves.

Uploaded by

Kashif Mujeeb
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 22

Object Oriented Programming

Exception Handling
Lecture 17
By
Irfan Latif Memon
outline
• Exception Handling and File I/O
• Uncaught exceptions
• Try, catch
• Throw, throws and final
Exception-Handling Fundamentals
• Exception Handling and File I/O
• Uncaught exceptions
• Try, catch
• Throw, throws and final
• File I/O
• Streams
• Simple file I/O
• Create a file
• Add the record to the file
• Read from existing file
Exception Handling
• The exception handling in java is one of the
powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
• Exceptions are thrown every time an error occurs.
Some examples:
• ArrayIndexOutOfBounds is thrown if the index that
does not exist in an array is accessed (e.g: Trying to
access arr[5], but arr only goes up to
arr[4]) ArithmeticError is thrown if an illegal arithmetic
operation is done (e.g: 42/0, division by zero)
Exception Handling
•  There are lots of exceptions that Java can
throw (more than the above).
• But, how can you handle exceptions, when
you're unsure if an error will occur.
• That's the purpose of try/catch! This is the
syntax for try/catch:
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. Let's take a scenario:
Exception Handling
• statement 1;  
• statement 2;  
• statement 3;  
• statement 4;  
• statement 5;//exception occurs  
• statement 6;  
• statement 7;  
• statement 8;  
• statement 9;  
• statement 10;  
• Suppose there is 10 statements in your program and there occurs an exception at
statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not
run. If we perform exception handling, rest of the statement will be executed.
That is why we use exception handling in java.
Java Exception Handling Keywords
• There are 5 keywords used in java exception
handling.
• try
• catch
• finally
• throw
• throws
Hierarchy of Java Exception classes
• 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  
•  
Java try block
• Java try block
• 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.
• Syntax of java try-catch
try{  
//code that may throw exception  
} catch(Exception_class_Name ref){}  
Syntax of try-finally block
• Syntax of try-finally block
try{  
//code that may throw exception  
}finally{}  
Syntax of try-finally block
• class TestFinallyBlock{  
•   public static void main(String args[]){  
•   try{  
•    int data=25/5;  
•    System.out.println(data);  
•   }  
•   catch(NullPointerException e){System.out.println(e);}  
•   finally{System.out.println("finally block is always executed");}  
•   System.out.println("rest of the code...");  
•   }  
• }  
Java catch block
• Java catch block is used to handle the
Exception. It must be used after the try block
only.
• You can use multiple catch block with a single
try.
Example

• public class Testtrycatch1{  
•   public static void main(String args[]){  
•       int data=50/0;//may throw exception  
•       System.out.println("rest of the code...");  
• }  
• }  
• public class Testtrycatch2{  
•   public static void main(String args[]){  
•    try{  
•       int data=50/0;  
•    }catch(ArithmeticException e)
– {System.out.println(e);}  
•    System.out.println("rest of the code...");  
• }  
• }  
Internal working of java try-catch
block
Internal working of java try-catch
block
• The JVM firstly checks whether the exception
is handled or not. If exception is not handled,
JVM provides a default exception handler that
performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods
where the exception occurred).
• Causes the program to terminate.
• But if exception is handled by the application
programmer, normal flow of the application is
throws
• If 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 exception.
• You do this by including a throws clause in the method’s
declaration. A throws clause lists the types of exceptions
that a method might throw. This is necessary for all
exceptions, except those of type Error or
RuntimeException, or any of their subclasses.
• All other exceptions that a method can throw must be
declared in the throws clause. If they are not, a compile-
time error will result.
throws
• This is the general form of a method declaration that includes a
throws clause:
• type method-name(parameter-list) throws exception-list
• {
• // body of method
• }
• Here, exception-list is a comma-separated list of the exceptions that
a method can throw.
• Following is an example of an incorrect program that tries to throw
an exception that it does not catch. Because the program does not
specify a throws clause to declare this fact, the program will not
compile.
throws
• // This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
throws
import java.io.IOException;  
class Testthrows1{  
  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[]){  
   Testthrows1 obj=new Testthrows1();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}  

You might also like