Exception Handling in Java
Tags: exceptionhandlinginjava, trycatchinjava, trycatchfinally, tryfinally
Published: 2020-08-07 16:44:34

<hr />

<h3>Table of Contents:</h3>
<ol>
 	<li><a href="#exceptions-in-java">Exception</a></li>
 	<li><a href="#checked-and-unchecked-exception">Checked and Unchecked Exception in java</a>
<ol>
 	<li><a href="#checked-exception">Checked Exception</a></li>
 	<li><a href="#unchecked-exception">UnChecked Exception</a></li>
</ol>
</li>
 	<li><a href="#difference-between-checked-and-unchecked-exception">Difference between checked and unchecked exception in java</a></li>
 	<li><a href="#try-catch-finally-block">Try Catch and finally block</a>
<ol>
 	<li><a href="#try-with-finally">Try with finally block</a></li>
</ol>
</li>
 	<li><a href="#custom-exception-in-java">Custom exception in Java With Example</a></li>
 	<li><a href="#try-with-multiple-catch-block">Try with multiple catch blocks in java with example</a></li>
 	<li><a href="#return-statement-in-exception-handling">Return statement in exception handling in Java with Example</a></li>
 	<li><a href="#exception-handling-in-method-overriding">Exception in case of method overriding</a></li>
</ol>
<img class=" wp-image-827 aligncenter" src="http://onlinetutorials.tech/wp-content/uploads/2020/08/Exception_handling_in_java-300x188.png" alt="Exception Handling In Java" width="558" height="349" />
<h2 id="exceptions-in-java">Exception in java</h2>
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s executions.
<h2 id="checked-and-unchecked-exception">Checked and Unchecked Exception</h2>
All the <strong>Exceptions</strong> which are not a child class of <strong>RuntimeException</strong> are called Checked Exception. We have to <strong>handle</strong> all Checked exception at compile time by using <strong>throws</strong> keywords or by using <strong>try-catch block</strong>
<h3 id="checked-exception">Examples of Checked Exception.</h3>
<ul>
 	<li>IOException</li>
 	<li>FileNotFoundException</li>
 	<li>ClassNotFoundException</li>
 	<li>CloneNotSupportedException</li>
 	<li>NoSuchMethodException</li>
 	<li>InterruptedException</li>
 	<li>NoSuchFieldException</li>
 	<li>ParseException</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.io.*;
class Exception { 
public static void main(String args[]) {
    FileInputStream fis = new FileInputStream("C:/Onlinetutorials"); 
    fis.close();
  }
}</pre>
The above code will not compile because <strong>FileInputStream</strong> constructor defined public <em><strong>FileInputStream(String name) throws FileNotFoundException</strong></em> which is <strong>checked exception</strong> and also close() method throws <strong>IOException</strong> which is also a checked <strong>exception</strong>. We need to do following changes in order to resolve the compilation error.

As we know checked exception <strong>must be handle at compile time</strong> either by <strong>using throws keyword or by using a try-catch block</strong>. So here firstly we are using throws keyword.
<h4>Using throws keyword:</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.io.*;
class Exception { 
public static void main(String args[]) throws Exception {
    FileInputStream fis = new FileInputStream("C:/Onlinetutorials"); 
    fis.close();
  }
}</pre>
<h4>Using try catch block:</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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();
    }
  }
}</pre>
<h2 id="unchecked-exception">Unchecked Exception</h2>
All Exceptions which are the subclass of <strong>RuntimeException</strong> is called <strong>unchecked</strong> exceptions. Like <strong>Checked</strong> exceptions, it is not mandatory to handle <strong>RuntimeExcepton</strong> 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.
<h3>Example of UnChecked Exception.</h3>
<ul>
 	<li>NullPointerException</li>
 	<li>ClassCastException</li>
 	<li>ArrayIndexOutOfBoundsException</li>
 	<li>IllegalStateException</li>
 	<li>NumberFormatException</li>
 	<li>IllegalArgumentException</li>
 	<li>IllegalMonitorStateException</li>
 	<li>IndexOutOfBoundsException</li>
</ul>
Let’s see an example that throws <strong>NullPointerException</strong>.
<pre class="EnlighterJSRAW" data-enlighter-language="generic">class NullPointerExample{ 
    public static void main(String args[]) {
    String s=null;
    System.out.println(s.hashCode());
  }
}</pre>
<h2 id="difference-between-checked-and-unchecked-exception">Difference between checked and unchecked exception in java</h2>
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell" style="text-align: center;"><strong>Checked Exception</strong></div>
<div class="divTableCell" style="text-align: center;"><strong>UnChecked Exception</strong></div>
</div>
<div class="divTableRow">
<div class="divTableCell">The Exception which are not subclass of RuntimeException are Checked Exception.</div>
<div class="divTableCell">This occuured only at runtime.</div>
</div>
<div class="divTableRow">
<div class="divTableCell">The Checked Exception must need to be handled at compile time either by using try catch or throws keyword</div>
<div class="divTableCell">This is not mandatory to handle.</div>
</div>
<div class="divTableRow">
<div class="divTableCell">Example is :FileNotFoundException/SQLException</div>
<div class="divTableCell">Example is :NullPointerException</div>
</div>
</div>
</div>
<h2 id="try-catch-finally-block">Try Catch and finally block</h2>
The catch block will execute only in case if we have some exception in the try block. The finally block will get always executed.
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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
    }
}
}</pre>
<h3 id="try-with-finally">Try finally block</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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");		
    }
}
}</pre>
<strong>Note –</strong> Finally block mainly used to perform release of resources clean up or session closing or database connection closing task.
<h2 id="custom-exception-in-java">Creating a custom exception in Java With Example</h2>
<strong>Custom Exception:</strong> Class created by extending Exception class or <strong>RuntimeException</strong> class is known as <strong>CustomException</strong>.
<h5>Steps to Create custom exception.</h5>
<ul>
 	<li>Create <strong>CustomException</strong> class(Mainly is application name) extending Exception or <strong>RuntimeException</strong> class.</li>
 	<li>Define one or two or more parametrized constructor.</li>
 	<li>In each constructor, Define super.</li>
 	<li>Use throw keyword to show the proper exception message.</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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());
        }
            
       }
}</pre>
<blockquote><strong>Output is –</strong>

com.onlinetutorials.tech.OnlineTutorialsException: Customer Id Cannot be null
at com.onlinetutorials.tech.OnlineTutorialsException.main(OnlineTutorialsException .java:20)</blockquote>
<h3><strong>Creating a custom exception extending RuntimeException class</strong></h3>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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");
        }							
    }
}</pre>
<blockquote><strong>Output is –</strong>

Exception in thread “main” com.onlinetutorials.tech.CustomException: problem in parsing the date
at com.onlinetutorials.tech.CustomException.main(CustomException.java:27)</blockquote>
<h2 id="try-with-multiple-catch-block">Try with multiple catch blocks in java with example</h2>
<ul>
 	<li>How to implement try with multiple catch blocks in <a href="https://onlinetutorials.tech/what-is-java-programming-language/">java</a>.</li>
 	<li>What is the benefit of multiple catch blocks? How to implement in the real-time scenario?</li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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);
    }
}
}</pre>
<h2 id="return-statement-in-exception-handling">Return statement in exception handling in Java with Example</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">package com.onlinetutorials.tech;

public class Example {
public static void main(String[] args) {
    try{		
        return;
        
    }catch(NullPointerException e) {
        System.err.println("catch block");
    }
    
}
}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">package com.onlinetutorials.tech;

public class Example2 {
public static void main(String[] args) {
    try{		
        return;
    }catch(NullPointerException e) {
        return;
    }finally {
        return;
    }		
}
}</pre>
<h2 id="exception-handling-in-method-overriding">Exception in case of method overriding</h2>
<strong>when the superclass method throws some exception.</strong>

Subclass overridden method can declare subclass exception or same exception(i.e declares in superclass) or no exception.
<pre class="EnlighterJSRAW" data-enlighter-language="generic">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();
  }
}</pre>
&nbsp;

Source: <a href="https://howtostartprogramming.in/category/exceptions/" rel="dofollow">Exception Handling in Java</a>
<hr />