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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last