Java throw Exception via throw keyword Tutorial

In this section, we will learn what the throw keyword is and how it works in Java.

What does throw exception mean in Java?

So far, we’ve learned that when a program is running, if something goes wrong, the runtime will automatically produce an exception. Of course, we can handle these exceptions via `try catch` blocks.

But other than the runtime engine, we can manually produce and throw exceptions as well.

After all, exceptions are nothing but objects of a set of prebuilt classes that inherit from `Throwable` class. So when we say “throw exception” it means to create and run a new exception.

How to throw exception in Java? (Java throw Keyword Syntax)

throw ExceptionObject;

To throw an exception, we use the keyword `throw` and on the right side of this statement we put the type of exception that we want to throw.

So the combination of the keyword `throw` and the target exception object creates the exception throwing statement.

Example: throwing exception via `throw` keyword

public class Simple {

    public static void main(String[] args) {
        checkAge(16);
    }
    public static void checkAge(int age){
        try{
            if (age <18){
                throw new IllegalArgumentException("Under legal age!");
            }else{
                System.out.println("Access granted!");
            }
        }catch (IllegalArgumentException exception){
            System.out.println(exception.getMessage());
        }
    }
}

Output:

Under legal age!

Inside the body of the `checkAge()` method, we’ve run a `try` block and via the `if` statement checked to see if the input argument to the method is less than 18.

Here, because the input value is in fact less than 18, we then created a new exception (object) of type `IllegalArgumentException` and as its message we set `Under legal age! ` and throw it via the `throw` keyword.

So now a new exception is thrown and the `catch` block of this `try` block is checked to see if the type of the exception matches the type of the parameter.

Because they matched, the body of the `catch` block ran and we’ve got the message you see in the output.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies