DEV Community

loading...

Java Tutorial - 6 Exception Handling

nadirbasalamah
A guy who interested in web development and software engineering
・3 min read

Exception handling is a recovery mechanism when an error or exception is occurred in a code. Exception handling is a useful tool to make sure the program or a code is still running although the exception is occurred.

Create an Exception Handling

To create an exception handling in Java can be done using try catch block. The try block contains the code that has a potential to throw an exception. The catch block contains the code that will be executed if the exception is occurred. This is the basic syntax of try catch block.

try {
    // code..
} catch(exception_type e) {
    // code..
}
Enter fullscreen mode Exit fullscreen mode

This is the example of using try catch to handle the exception.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 0;
            // print out the result
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Exception: / by zero

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the exception is occurred in this code, then the code inside catch block is executed to print the exception's message. The exception is occurred because the division by zero is not possible so the exception is thrown or occurred.

The finally block is also available. Basically, the code inside finally block is executed although the code throw an exception or not.

This is the example of using finally block.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 0;
            // print out the result
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        } finally {
            // execute this code
            System.out.println("I'm done!");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Exception: / by zero
I'm done!

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the code inside finally block is still executed although the exception is thrown.

In this code, the finally block is still executed although the code is executed successfully.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 10;
            // print out the result
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        } finally {
            // execute this code
            System.out.println("I'm done!");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Result: 2
I'm done!

Enter fullscreen mode Exit fullscreen mode

If the exception occurred inside the try block, the rest of the codes inside try block is ignored.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute the division operation
            int num = 20 / 0; // exception is thrown here.
            // this code is ignored
            System.out.println("Result: " + num);
        } catch (Exception e) {
            // print the exception's message if exception is occurred
            System.out.println("Exception: " + e.getMessage());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Create a Custom Exception

Exception can be thrown by a function. To indicate a certain function is throwing an exception. Use the throws keyword after the function declaration.

// example
public static int sum(int[] nums) throws Exception { }
Enter fullscreen mode Exit fullscreen mode

The function's exception can be handled using try catch block. This is the example of using throws in a function.

public class MyApp {
    public static void main(String[] args) {
        try {
            // execute a function that throws an exception
            regularFunc(1000);
        } catch (Exception e) {
            // get the exception's message
            System.out.println("Message: " + e.getMessage());
        }
    }

    // create a function that throws RuntimeException
    public static void regularFunc(int num) throws RuntimeException {
        if (num > 100)
            throw new RuntimeException("It's too much!");
        else
            System.out.println("Good to go!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Message: It's too much!

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the exception is thrown and the code inside catch block is executed. notice that the exception's message is defined inside the RuntimeException() method's argument in the regularFunc() function.

Sources

  • Learn more about exception in this link.

I hope this article is helpful for learning the Java programming language. If you have any thoughts or comments you can write in the discussion section below.

Discussion (0)

Forem Open with the Forem app