Java Tutorial - 6 Exception Handling
Tags: java, tutorial, beginners
Published: 2021-06-07 00:27:54

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..
}
```

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

```java
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());
        }
    }
}

```

Output

```
Exception: / by zero

```

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.

```java
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!");
        }
    }
}

```

Output

```
Exception: / by zero
I'm done!

```

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.

```java
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!");
        }
    }
}

```

Output

```
Result: 2
I'm done!

```

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

```java
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());
        }
    }
}
```

## 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 { }
```

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

```java
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!");
    }
}

```

Output

```
Message: It's too much!

```

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](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html).

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.