Skip to main content

What is Exception and Exception handling in Java | Programming Blog

Exception and Exception handling in Java with examples

What is Exception?

Exception is event, which occurs during the execution of a program, that disrupts the normal flow of program's instructions.

In simple word, Exception is unwanted event that interrupts the normal flow of program. When Exception is occurs during program execution it gets terminated.

Why Exception occurs?

There may be several reason for occurs the Exception. Like,

  • When you try to assign value into array index that is not present.
  • When you divide any number using 0.
  • File is not present at given location.
  • During casting. like String to Integer.

So, there are so many reasons for occurs the Exception.

See example of java.lang.ArithmeticException: / by zero Exception

public class SimpleClass{

    public static void main(String[] args) {
       
        int a = 10/0;
    }

}

Output :-
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at SimpleClass.main(SimpleClass.java:5)

Types of Exceptions in Java

Checked and Unchecked exceptionand its hirarchy in Java
Java Exception Hierarchy
 

Types of exception in java.

  1. Checked Exception
  2. Unchecked Exception
  3. Error

So lets see above two types in details.

1. Checked Exception

Checked Exception are also called compile time exception. Compile time exception is checked at compile time. 

Compiler checks during compilation to see whether the programmer has handled them or not. I the exception are not handled or declared in program you will get compilation error.

When we use code that can throw checked exceptions, we must handle them, otherwise the program does not compile. 

We can handle Checked exception using try catch block or throws the exception using throws keyword.

Checked exceptions give API designers the power to force programmers to deal with the exceptions. API designers expect programmers to be able to reasonably recover from those exceptions.

All exceptions other than Runtime Exceptions are known as Checked exceptions. 

You must handle or throws the Checked exception 

Some examples of Checked exceptions are:-

  1. ClassNotFoundException
  2. IllegalAccessException
  3. NoSuchFieldException
  4. NoSuchMethodException
  5. SQLException

See example of Checked exception :-

import java.io.FileWriter;

public class ExceptionDemo {

    public static void main(String[] args) {
        
        String filePath = "hello.txt";
        String text = "Hello World";
        
        createFile(filePath, text);
    }
    
    public static void createFile(String path, String text) {
        FileWriter writer = new FileWriter(path, true);
        writer.write(text);
        writer.close();
    }

}

Above example gives following Exception :-

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    Unhandled exception type IOException
    Unhandled exception type IOException
    Unhandled exception type IOException

    at ExceptionDemo.createFile(ExceptionDemo.java:14)
    at ExceptionDemo.main(ExceptionDemo.java:10)

If you are using any IDE then it gives following suggestion.

Checked exception in java with examples

Check out other Exceptions also :-

2. Unchecked Exception

Unchecked exception are also called run time exception. Run time exception is checked at run time.

Errors and Run time Exceptions are Unchecked.

Compiler does not enforce you to handle them like Checked exceptions. It is your choice.

Some list of Unchecked exceptions :-

  1. ArithmeticException
  2. ClassCastException
  3. IndexOutOfBoundsException
  4. NullPoinerException

Example of Unchecked exception :-

public class ExceptionDemo {

    public static void main(String[] args) {
        divideValue(10, 0);
    }
    
    public static void divideValue(int value1, int value2) {
       System.out.println(value1 / value2);
    }

}

Output :-
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at ExceptionDemo.divideValue(ExceptionDemo.java:8)
    at ExceptionDemo.main(ExceptionDemo.java:4)


Unchecked exception in java with example

You can see in above image that it is not compulsory to handle Unchecked exception. but if you want to handle then you can write try catch block or throws exception.

public class ExceptionDemo {

    public static void main(String[] args) {
        divideValue(10, 0);
    }
    
    public static void divideValue(int value1, int value2) {
        try {
            System.out.println(value1 / value2);
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Unchecked Exception Handled");
        }
    }

}

Output :-
Unchecked Exception Handled


public class ExceptionDemo {

    public static void main(String[] args) {
        try {
            divideValue(10, 0);
        } catch (Exception e) {
            System.out.println("Unchecked Exception Handled");
        }
    }
    
    public static void divideValue(int value1, int value2) throws Exception {
        System.out.println(value1 / value2);
    }

}


3. Error

These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. 

For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError.

An application might choose to catch this exception, in order to notify the user of the problem but it also might make sense for the program to print a stack trace and exit.

Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

Check out Java Doc for Exception.

Check out difference between throw and throws in Java.

Comments

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...