How do I handle exceptions using try-catch block?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions. When an abnormal situation occurs within a method, an Exception object is thrown. This object contains information about the error or unusual problems that occur.

Creating an exception object and handing it to the runtime system is called throwing an exception.
If you want to deal with the exceptions where they occur, you can include three kinds of code blocks in a method to handle them. try, catch, and finally blocks.

  • The try block encloses code that may give rise to one or more exceptions
  • The catch block encloses code that is intended to handle exceptions of a particular type that may be thrown in the associated try block
  • The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.

 

package org.kodejava.example.fundamental;

public class ExceptionHandlerExample {

    public static void main(String[] args) {
        int x = 1, y = 0, z = 0;

        try {
            //
            // divide by 0 will thrown an exception
            //
            z = ExceptionHandlerExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     * @throws RuntimeException when an exception occurs.
     */
    private static int divide(int x, int y) throws RuntimeException {
        return x / y;
    }
}

Here is what happening when we run the program:

java.lang.ArithmeticException: / by zero
	at org.kodejava.example.fundamental.ExceptionHandlerExample.divide(ExceptionHandlerExample.java:30)
	at org.kodejava.example.fundamental.ExceptionHandlerExample.main(ExceptionHandlerExample.java:12)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Finally block is always executed.
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply