# Exception Handling in Java

In 
Published 2022-12-03

# Exception Handling in Java - theory

Take a look at the following picture:

Here are the things you have to know about errors & exceptions in Java :

  • The Runtime Exception are not checked because normally, this kind of exception are avoided using a good code. The code must be as long as we need, no longer.

  • Runtime Exceptions are caused by bad programming. Supposing you want to read 4 elements from a 3 element array ... in this case you will receive ArrayIndexOutOfBoundException.

  • The Other exceptions are exceptional scenarios that we can anticipate in the code and we want to have care of that particular situation. Supposing in a normal situation we receive a file at 10:00am and our java program will run at 10:10am to do something with that file. We anticipate that sometime the file will arrive at 10:30. In this case when the file is not found at 10:10 we deal with a IOException and we will retry the task later.

  • An exception is an event that disrupts the normal flow of the program and is directly related to the Java code.

  • An error is an event that disrupts the normal flow of the program and is NOT directly related to the Java code. For this reason, generally, the errors are hard to anticipate. Errors appear because of the JVM or because of the hardware.

  • An IOError could appear because of the hardware (the storage is down, for instance).

  • The Errors are not checked because are rare, and generally we cannot do something in order to avoid the problem.

  • The Other Exceptions are checked because we anticipate them, and we want to do something in that case.

# Example #1 - Exception Handling in Java

Here is an example without exception handling:

class ExceptionDemo1 {

  public static void main(String[] args) {
  int a=10;
  int b=0;
  int c;
  
  c= a/b;
  System.out.println("You cannot divide by zero.");      
  }
}

When you run this code you receive the following error:

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

... but if we are handling the exception ...

class ExceptionDemo1 {

  public static void main(String[] args) {
      int a=10;
      int b=0;
      int c;
      
      try   {
         c= a/b;
      } catch (Exception e)  {
         System.out.println("You cannot devide by zero.");  
      }  

  }
}

Here is the new result if we handle the exception:

You cannot devide by zero.

In this example we handle the exception ArithmeticException but without writing the name ArithmeticException in clear. This is a coding error and we need to avoid this situation !

The general syntax for handling exceptions is:

try {
   // statements which could raise an exception
   
} catch(exception-type1 object1) {
   // statements which run in case of exception-type1
   
} catch(exception-type2 object2) {
   // statements which run in case of exception-type2

} finally {
   // statements which run all the time after try & catch blocks
   
}

# Example #2 - Custom exception handling in Java

The following example is showing how the custom exception are created and used.

Firstly, we need to create the custom exception:

package com.example.demo;

public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
}

and now we can use the custom exception :

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo1Application.class, args);

		try {

			throw new MyException("Something wrong happened");

		} catch (MyException e) {
			System.out.println("An error happened - ABC !");;
		}
	}
}

When we run this Spring Boot application we will see:

An error happened - ABC !

Process finished with exit code 0

If the try ... catch block is removed (and "throws MyException" is added), the code will look like this:

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Demo1Application {

    public static void main(String[] args) throws MyException {
        SpringApplication.run(Demo1Application.class, args);

		throw new MyException("Something wrong happened");
	}
}

When we run this Spring Boot application we will see:

Exception in thread "main" com.example.demo.MyException: Something wrong happened
	at com.example.demo.Demo1Application.main(Demo1Application.java:12)

Process finished with exit code 1

Enjoy handling exception in Java !