You are on page 1of 11

EXCEPTION HANDLING

What is Exception in Java?


Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the


program.

It is an object which is thrown at runtime.

Advantage of exception handling is to maintain the normal flow of the


application execution

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as

ClassNotFoundException,

IOException,

SQLException,

RemoteException, etc

Example:

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5;//exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;   Rest of the Code
9. statement 9;  
10. statement 10;  
Exception Example:
-----------------------------------------------------------------------------------
Divide(int a) throws ArithmeticException
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 

Hierarchy of Java Exception classes


Types of Java Exceptions

Difference between Checked and Unchecked


Exceptions
1) Checked Exception - checked at compile-time

The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions.

For example, IOException, SQLException, etc. Checked exceptions are


checked at compile-time.

Eg:

public ArrayList<Customer> getAllCustomer() throws SQLException, ClassNotFoundException


2) Unchecked Exception - RuntimeException

The classes that inherit the RuntimeException are known as unchecked


exceptions.

For example, ArithmeticException, NullPointerException,


ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime .

3) Error

Error is irrecoverable.

Example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Example Code1:

public class JavaExceptionExample{  
  public static void main(String args[]){  

   try{  
      //code that may raise exception  

      int data=100/0;  
   }catch(ArithmeticException e){System.out.println(e);}  

   //rest code of the program   
   System.out.println("rest of the code...");  

  }  
}  
Example Code2:

public class MultipleCatchBlock1 {  
  
    public static void main(String[] args) {  
          
           try{    
                int a[]=new int[5];    
                a[5]=30/0;    
               }    
               catch(ArithmeticException e)  
                  {  
                   System.out.println("Arithmetic Exception occurs");  
                  }    
               catch(ArrayIndexOutOfBoundsException e)  
                  {  
         System.out.println("ArrayIndexOutOfBounds Exception occurs");  
                  }    
               catch(Exception e)  
                  {  
                   System.out.println("Parent Exception occurs");  
                  }             
               System.out.println("rest of the code");    
    }  

Java finally block


Java finally block is a block used to execute important code such as

closing the connection, etc.

Java finally block is always executed whether an exception is handled or

not.
Therefore, it contains all the necessary statements that need to be

printed regardless of the exception occurs or not.

The finally block follows the try-catch block.

Flowchart of finally block

Why use Java finally block?


o finally block in Java can be used to put "cleanup" code such as
closing a file, closing connection, etc.
o The important statements to be printed can be placed in the finally
block.
Example:

public class TestFinallyBlock1{    
      public static void main(String args[]){   
  
      try {    
  
        System.out.println("Inside the try block");  
          
        //below code throws divide by zero exception  
       int data=25/0;    
       System.out.println(data);    
      }    
      //cannot handle Arithmetic type exception  
      //can only accept Null Pointer type exception  
      catch(NullPointerException e){  
        System.out.println(e);  
      }   
  
      //executes regardless of exception occured or not   
      finally {  
        System.out.println("finally block is always executed");  
      }    
  
      System.out.println("rest of the code...");    
      }    
    }   

EXCEPTION : Throw

Throws:

throws IOException,NullPointerException, ArrayIndexOutOfBoundsException

Syntax:

Syntax: public return_type method_name() throws ExceptionType1, ExceptionType2


Example: public int add(int a,int b) throws IOException,NullPointerException

The Java throws keyword is used to declare an exception. It

gives an information to the programmer that there may occur an

exception so it is better for the programmer to provide the exception

handling code so that normal flow can be maintained.

What is the use of throw block?

The throws keyword is used to declare which exceptions can be thrown

from a method, while the throw keyword is used to explicitly throw an

exception within a method or block of code. The throws keyword is

used in a method signature and declares which exceptions can be

thrown from a method

Example:

/*

* To change this template, choose Tools | Templates

* and open the template in the editor.

*/

package arraylistcustomerdb;

import java.sql.*;

import java.util.*;

import java.util.logging.Level;

import java.util.logging.Logger;
class Customer {

private String id;

private String name;

private String salary;

private String address;

public String getId() {

return id;

public void setId(String id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getSalary() {

return salary;

public void setSalary(String salary) {

this.salary = salary;

public String getAddress() {

return address;

public void setAddress(String address) {

this.address = address;

}
public class ArrayListCustomerDB

public ArrayList<Customer> getAllCustomer() throws ClassNotFoundException, SQLException

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wtlab","root", "");

Statement stmt = con.createStatement();

ResultSet rs;

String sql = "Select * From Customer";

rs = stmt.executeQuery(sql);

ArrayList<Customer> customerList = new ArrayList<>();

while (rs.next())

Customer customer = new Customer();

customer.setId(rs.getString("id"));

customer.setName(rs.getString("name"));

customer.setAddress(rs.getString("address"));

customer.setSalary(rs.getString("salary"));

customerList.add(customer);

return customerList;

public static void main(String[] args) throws SQLException

ArrayListCustomerDB obj=new ArrayListCustomerDB();

try {

ArrayList<Customer> customerlist = obj.getAllCustomer();

for (int i = 0; i < customerlist.size(); i++)

System.out.println(customerlist.get(i).getId());

System.out.println(customerlist.get(i).getName());
System.out.println(customerlist.get(i).getSalary());

System.out.println(customerlist.get(i).getAddress());

catch (ClassNotFoundException ex) {

Logger.getLogger(ArrayListCustomerDB.class.getName()).log(Level.SEVERE, null, ex);

You might also like