JAVA - Zero to Hero / Exception Handling

Throw and Throws

Why throw and throws?

Sometimes, you want to:

  • πŸš€ Manually throw an exception in your code β†’ use throw

  • πŸ“ Declare that a method might throw an exception β†’ use throws

Both are useful when you're creating custom logic or delegating exception handling.


πŸ™ŒπŸ» throw Keyword

The throw keyword is used to explicitly throw an exception β€” either a built-in or a custom one.

πŸ”§ Syntax:

throw new ExceptionType("message");

βœ… Example: Using throw

public class Main {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Not eligible to vote");
        } else {
            System.out.println("You can vote");
        }
    }

    public static void main(String[] args) {
        checkAge(16);  // Manually throwing exception
    }
}
Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote

πŸ”Ή Note:

  • Only one exception can be thrown using throw

  • throw is followed by a new instance of Throwable (Exception or subclass)


πŸ”· What is Throwable in Java?

Throwable is a class in the java.lang package, and it is the superclass of all errors and exceptions that can be thrown and caught by the Java Virtual Machine (JVM).

In simple terms:

Anything that can be "thrown" as an error or exception in Java must be a subclass of Throwable.


πŸ”§ Purpose of Throwable:

  • To define a common type for all objects that represent problems during program execution.

  • It allows the use of try-catch blocks to handle problems in a uniform way.

  • Java's exception-handling mechanism is built on top of the Throwable class


πŸ™ŒπŸ» throws Keyword

The throws keyword is used to declare that a method might throw an exception, so the caller should handle it.

πŸ”§ Syntax:

returnType methodName() throws ExceptionType {
    // method body
}

βœ… Example: Using throws

public class Main {

    // This method declares that it might throw an Exception
    static void checkAge(int age) throws Exception {
        if (age < 18) {
            throw new Exception("You must be 18 or older");
        } else {
            System.out.println("Access granted");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(15);  // This will throw an exception
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}
Exception caught: You must be 18 or older

πŸ” throw vs throws β€” Quick Comparison

Feature

throw

throws

Use Case

Used to actually throw an exception

Used to declare potential exceptions

Placement

Inside a method

In method signature

Quantity

Only one exception at a time

Can declare multiple exceptions

Example

throw new Exception();

void f() throws IOException {}