Exceptions in Java

Exception

In the previous blog we learned about the Inner Classes in Java. If you want to learn about the Inner Class then visit Inner Classes in Java . In this blog, we will go through Exceptions, Assertions, and Logging. Exceptions are unwanted or unexpected events that occur during a program's execution, i.e. at run time, and interrupt the normal flow of the program's instruction. Exceptions are caught and handled programmatically. It is not every time that our code works as expected without any bugs in it. There are times when our code has bugs or some external circumstances due to which it may be possible that the user may lose the work which he did during that particular session, in this case, the user will never visit our application. To overcome this situation Java has introduced the concept called exception handling. We will go through it in detail in the following sections:


Dealing with Errors in Java

Let's consider an example if our program is running and suddenly an error occurs and that error is caused due to wrong information contained in a file or network connection issues or invalid array index or object references. The user thinks or expects that the program will still run when the error occurs. If the operations remain incomplete due to the error then the program must return to the safe state and enable the user to perform other commands or the user should be allowed to save all his work and exit without any issues. So to deal with this situation Java has introduced exception handling wherein its mission is to transfer the control from where the error occurred to an error handler that can deal with the situation. We must take into consideration the errors that may occur when we are running our program

  1. User Input errors
  2. Device errors
  3. Physical limitations
  4. Code errors

Exception Hierarchy in Java

In Java an exception object is an object of the class derived from Throwable. We can even create an exception if the requirements are not fulfilled by the built-in exceptions.

...

Types of Exceptions

Following are the types of Exceptions:

...

There are two types of Exception

  1. Checked Exception
  2. Unchecked Exception
  1. Checked Exception
  2. Checked Exceptions are the exceptions that are checked by the compiler during compile time. These exceptions cannot be ignored. We must handle them otherwise the program gets terminated if these exceptions occur.

    e.g.

    import java.io.*;
    public class TestFileNotFoundExceptionExample{
      public static void main(String[] args){
        FileReader fileReaderObj = new    FileReader("Atrowel.txt");
        BufferedReader bufferReaderObj = new BufferedReader(fileReaderObj);
        String file = null;
        while ((file = bufferReaderObj.readLine()) != null){
          System.out.println(file);
        }
        try {
          bufferReaderObj.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
      }
    }

    Output

    error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    FileReader fileReaderObj = new FileReader("Atrowel.txt");
    
    error: unreported exception IOException; must be caught or declared to be thrown
    while ((file = bufferReaderObj.readLine()) != null)
  3. Unchecked Exceptions
  4. Unchecked Exceptions are the exceptions that occur at the time of execution. So these exceptions are called Runtime exceptions. These exceptions occur due to logic errors, improper use of API, etc. The compiler ignores this exception at compile time.

    e.g. Example of ArithmeticException

    public class TestArithmeticExceptionExample{
      public static void main(String[] args){
        int testData1 = 90;
        int testData2 = 0;
        int result = testData1/testData2;
        System.out.println(result);
    
      }
    }

    Output

    Exception in thread "main" java.lang.ArithmeticException: / by zero at TestArithmeticExceptionExample.main(TestArithmeticExceptionExample.java:8)

    e.g.Example of NullPointerException

    public class TestNullPointerExceptionExample{
      public static void main(String[] args){
        String testStr = null;
        System.out.println(testStr.length());
    
      }
    }

    Output

    Exception in thread "main" java.lang.NullPointerException at TestNullPointerExceptionExample.main(TestNullPointerExceptionExample.java:7)

    e.g. Example of ArrayIndexOutOfBoundException

    public class TestArrayIndexOutOfBoundExceptionExample{
      public static void main(String[] args){
        int testArray[] = {3,6,9,7};
        System.out.println(testArray[10]);
    
      }
    }

    Output

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 4 at TestNullPointerExceptionExample.main(TestNullPointerExceptionExample.java:7)

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.