DEV Community

Anees Abdul
Anees Abdul

Posted on

Java Exception Handling

What is Exception:
An exception is an unexpected event that disrupts the normal execution of the program or application
An exception can occur for many reasons. Some of them are:
-Invalid user input
-Device failure
-Loss of network connection
-Code errors
-Opening an unavailable file

                Throwable
                   │
        ┌──────────┴──────────┐
        │                     │
      Error               Exception
                              │
                 ┌────────────┴────────────┐
                 │                         │
         RuntimeException              IOException
         (Unchecked)                    (Checked)


Enter fullscreen mode Exit fullscreen mode

Throwable:
-It is the root class of all exceptions and errors.
-It has two branches-
*Error
*Exception

Error:
-It is a problem related to JVM that runs out of memory or stack overflow etc.

Exception:
-Exceptions can be caught and handled by the program. When the exception occurs, It contains information about the exception such as the name and description of the exception and state of the program when the exception occurred.

Java Exception Types:
1.Checked Exception
2.UnChecked Exception

1.Checked Exception:
-It is also know as compile time or IO Exception
-JDK will detect the compile time exception and it should be fixed before the program runs

Some of the examples of checked exceptions are:

Checked Exceptions
          │     ├── IOException(File/stream error)
          │     ├── SQLException(Database error)
          │     └── FileNotFoundException(File missing)
Enter fullscreen mode Exit fullscreen mode

2.UnChecked Exception:
-It is also know as Run time Exception.
-It occurs because of mistakes in the programs

Some of the examples of Unchecked Exceptions are:

RuntimeException (Unchecked)
           ├── NullPointerException(Missing Variable initialization)
           ├── ArithmeticException(Dividing a number by 0)
           ├── ArrayIndexOutOfBoundsException(Out-of-bounds array access)
           └── IllegalArgumentException(Improper use of an API )
Enter fullscreen mode Exit fullscreen mode

What is Exception Handling:
-It is a mechanism to handle the run time exception using try, catch, finally, throw, and throws to maintain normal application flow.

Different approaches to handle exceptions in Java:
1.try
2.catch
3.finally
4.throw
5.throws

1.try block:
-It is used to monitor the exception.

try {
  // code
}
Enter fullscreen mode Exit fullscreen mode

Here, we have placed the code that might generate an exception inside the try block. Every try block is followed by a catch block.

2.Catch block:
-It is used to handle the exception

catch(Exception e) {
  // code
}
Enter fullscreen mode Exit fullscreen mode

When an exception occurs, it is caught by the catch block. The catch block cannot be used without the try block.

Example Program using try and catch:

class Main {
  public static void main(String[] args) {

    try {

      // code that generate exception
      int divideByZero = 5 / 0;
      System.out.println("Rest of code in try block");
    }

    catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
  }
}

Enter fullscreen mode Exit fullscreen mode
O/P: ArithmeticException => / by zero
Enter fullscreen mode Exit fullscreen mode

In the example, we are trying to divide a number by 0. Here, this code generates an exception. To handle the exception, we have put the code, 5 / 0 inside the try block. Now when an exception occurs, the rest of the code inside the try block is skipped.

The catch block catches the exception and statements inside the catch block is executed.

If none of the statements in the try block generates an exception, the catch block is skipped.

3. finally block:

-This block is always executed no matter whether there is an exception or not.
-The finally block is optional. And, for each try block, there can be only one finally block.

finally {
  // finally block always executes
}

Enter fullscreen mode Exit fullscreen mode

-If an exception occurs, the finally block is executed after the try...catch block. Otherwise, it is executed after the try block.

  • It is a good practice to use the finally block. Because, it can includes clean up codes like closing a file or connection

4. throw block:
-The throw keyword is used to explicitly throw a single exception.

  • Used inside the method body
  • Used to throw a single exception
  • Followed by a new keyword
  • Transfers control to the nearest catch block
public class Test {

    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or above");
        }
        System.out.println("Eligible to vote");
    }

    public static void main(String[] args) {
        checkAge(16);
    }
}
Enter fullscreen mode Exit fullscreen mode

5. throws block:
-We use the throws keyword in the method declaration to declare the type of exceptions that might occur within it.

accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 … {
  // code
}
Enter fullscreen mode Exit fullscreen mode

Example Program:

class Main {
  public static void findFile() throws IOException {
    // code that may produce IOException
    File newFile=new File("test.txt");
    FileInputStream stream=new FileInputStream(newFile);
  }

  public static void main(String[] args) {
    try{
      findFile();
    } catch(IOException e){
      System.out.println(e);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

-When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException, which extends the IOException class.

Top comments (0)