rajesh1761

Rajesh Mishra

Posted on August 7, 2020

Exception Handling in Java

Table of Contents:

  1. Exception
  2. Checked and Unchecked Exception in java
    1. Checked Exception
    2. UnChecked Exception
  3. Difference between checked and unchecked exception in java
  4. Try Catch and finally block
    1. Try with finally block
  5. Custom exception in Java With Example
  6. Try with multiple catch blocks in java with example
  7. Return statement in exception handling in Java with Example
  8. Exception in case of method overriding


Exception Handling In Java

Exception in java

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s executions.

Checked and Unchecked Exception

All the Exceptions which are not a child class of RuntimeException are called Checked Exception. We have to handle all Checked exception at compile time by using throws keywords or by using try-catch block

Examples of Checked Exception.

  • IOException
  • FileNotFoundException
  • ClassNotFoundException
  • CloneNotSupportedException
  • NoSuchMethodException
  • InterruptedException
  • NoSuchFieldException
  • ParseException
import java.io.*;
class Exception { 
public static void main(String args[]) {
    FileInputStream fis = new FileInputStream("C:/Onlinetutorials"); 
    fis.close();
  }
}

The above code will not compile because FileInputStream constructor defined public FileInputStream(String name) throws FileNotFoundException which is checked exception and also close() method throws IOException which is also a checked exception. We need to do following changes in order to resolve the compilation error.

As we know checked exception must be handle at compile time either by using throws keyword or by using a try-catch block. So here firstly we are using throws keyword.

Using throws keyword:

import java.io.*;
class Exception { 
public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream("C:/Onlinetutorials"); 
    fis.close();
  }
}

Using try catch block:

import java.io.*;
class Exception { 
public static void main(String args[]) {
try {
    FileInputStream fis = new FileInputStream("C:/Onlinetutorials"); 
    fis.close();
}catch (Exception e) {
    e.printStackTrace();
    }
  }
}

Unchecked Exception

All Exceptions which are the subclass of RuntimeException is called unchecked exceptions. Like Checked exceptions, it is not mandatory to handle RuntimeExcepton by using throws keyword or try-catch block. If we do some programming mistakes then JVM will automatically throw a runtime exception. It will always happen at runtime.

Example of UnChecked Exception.

  • NullPointerException
  • ClassCastException
  • ArrayIndexOutOfBoundsException
  • IllegalStateException
  • NumberFormatException
  • IllegalArgumentException
  • IllegalMonitorStateException
  • IndexOutOfBoundsException

Let’s see an example that throws NullPointerException.

class NullPointerExample{ 
    public static void main(String args[]) {
    String s=null;
    System.out.println(s.hashCode());
  }
}

Difference between checked and unchecked exception in java

Checked Exception
UnChecked Exception

The Exception which are not subclass of RuntimeException are Checked Exception.
This occuured only at runtime.

The Checked Exception must need to be handled at compile time either by using try catch or throws keyword
This is not mandatory to handle.

Example is :FileNotFoundException/SQLException
Example is :NullPointerException


Try Catch and finally block

The catch block will execute only in case if we have some exception in the try block. The finally block will get always executed.

public class ExceptionHandling{
public static void main(String[] args) {
    try{
               //Custom logic
    }catch(Exception e){
        // if some exception will come inside try block 
        //then only catch block will execute    
    }finally {
        //it will execute always even exception comes inside try block or not
    }
}
}

Try finally block

public class TryWithFinally{
public static void main(String[] args) {
    try{        
        String stringVariable = "OnlineTutorials";
        System.out.println("value of stringVariable "+stringVariable);      
    }finally {
        System.out.println("finally block executed");       
    }
}
}

Note – Finally block mainly used to perform release of resources clean up or session closing or database connection closing task.

Creating a custom exception in Java With Example

Custom Exception: Class created by extending Exception class or RuntimeException class is known as CustomException.

Steps to Create custom exception.
  • Create CustomException class(Mainly is application name) extending Exception or RuntimeException class.
  • Define one or two or more parametrized constructor.
  • In each constructor, Define super.
  • Use throw keyword to show the proper exception message.
package com.onlinetutorials.tech;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OnlineTutorialsException extends Exception{
        public OnlineTutorialsException (String message) {
            super(message);
        }
        public OnlineTutorialsException (String message, Throwable t) {
            super(message, t);
        }
           public static void main(String[] args) {
        try {
           String customerId= null;
                   if(customerId== null) {
                throw new OnlineTutorialsException("Customer Id Cannot be null ");
               }
        }catch(Exception e) {
            System.err.print(e.printStackTrace());
        }
            
       }
}
Output is – com.onlinetutorials.tech.OnlineTutorialsException: Customer Id Cannot be null at com.onlinetutorials.tech.OnlineTutorialsException.main(OnlineTutorialsException .java:20)

Creating a custom exception extending RuntimeException class

package com.onlinetutorials.tech;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class CustomException extends RuntimeException{
     public CustomException (String message) {
            super(message);
        }
     public CustomException (String message, Throwable t) {
            super(message, t);
     }
    public static void main(String[] args) {        
        String dateAsString = "11101988";       
        DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");        
        try {
            Date date = dateFormat.parse(dateAsString);
        }catch(Exception e) {
            throw new CustomException("problem in parsing the date");
        }                           
    }
}
Output is – Exception in thread “main” com.onlinetutorials.tech.CustomException: problem in parsing the date at com.onlinetutorials.tech.CustomException.main(CustomException.java:27)

Try with multiple catch blocks in java with example

  • How to implement try with multiple catch blocks in java.
  • What is the benefit of multiple catch blocks? How to implement in the real-time scenario?
package com.onlinetutorials.tech;

public class TryWithMultipleCatch{
public static void main(String[] args) {
    try {
    //Custom logic
    }catch(NullPointerException n) {
        System.err.println(n);
    }catch(RuntimeException r) {
        System.err.println(r);
    }catch(Exception e) {
        System.err.println(e);
    }
}
}

Return statement in exception handling in Java with Example

package com.onlinetutorials.tech;

public class Example {
public static void main(String[] args) {
    try{        
        return;
        
    }catch(NullPointerException e) {
        System.err.println("catch block");
    }
    
}
}
package com.onlinetutorials.tech;

public class Example2 {
public static void main(String[] args) {
    try{        
        return;
    }catch(NullPointerException e) {
        return;
    }finally {
        return;
    }       
}
}

Exception in case of method overriding

when the superclass method throws some exception.

Subclass overridden method can declare subclass exception or same exception(i.e declares in superclass) or no exception.

import java.io.FileNotFoundException;
import java.io.IOException;
class Vehicle{
    public void m1() throws IOException{
    System.out.println("super class method");
  }
}
class Car extends Vehicle{
    // subclass exception
    public void m1() throws FileNotFoundException{
    System.out.println("sub class method");
  }
}
public class Test4 {
    public static void main(String[] args) throws Exception{
    Vehicle vehicle=new Car();
    vehicle.m1();
  }
}

 

Source: Exception Handling in Java


💖 💪 🙅 🚩
rajesh1761
Rajesh Mishra

Posted on August 7, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Exception Handling in Java
exceptionhandlinginjava Exception Handling in Java

August 7, 2020