Throwing an Exception

Introduction

throw keyword is used to manually throw an exception.


Basic Syntax

throw new ExceptionType("Error message");

Simple Example

public class Main {
    static void checkAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Age must be 18+");
        }
        System.out.println("Valid age");
    }

    public static void main(String[] args) {
        try {
            checkAge(15);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output: Age must be 18+


throw vs throws

Featurethrowthrows
PurposeThrow exceptionDeclare exception
LocationInside methodMethod signature
Syntaxthrow new Exception()throws Exception
Examplethrow new IOException()void m() throws IOException

Throwing Checked Exception

import java.io.*;

class FileValidator {
    // Must declare with throws
    void validateFile(String filename) throws IOException {
        if (filename == null) {
            throw new IOException("Filename cannot be null");
        }
        System.out.println("Valid file");
    }
}

public class Main {
    public static void main(String[] args) {
        FileValidator validator = new FileValidator();
        try {
            validator.validateFile(null);
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Throwing Unchecked Exception

class Calculator {
    // No need to declare
    static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return a / b;
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println(Calculator.divide(10, 0));
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }
    }
}

Validation Example

class Voter {
    String name;
    int age;

    Voter(String name, int age) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("Name cannot be empty");
        }
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Invalid age");
        }
        this.name = name;
        this.age = age;
    }

    void vote() {
        if (age < 18) {
            throw new IllegalStateException("Too young to vote");
        }
        System.out.println(name + " voted");
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            Voter v1 = new Voter("John", 20);
            v1.vote();

            Voter v2 = new Voter("Alice", 15);
            v2.vote();
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid input: " + e.getMessage());
        } catch (IllegalStateException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Re-throwing Exception

public class Main {
    static void method1() throws Exception {
        throw new Exception("Error in method1");
    }

    static void method2() throws Exception {
        try {
            method1();
        } catch (Exception e) {
            System.out.println("Caught in method2");
            throw e;  // Re-throw
        }
    }

    public static void main(String[] args) {
        try {
            method2();
        } catch (Exception e) {
            System.out.println("Caught in main: " + e.getMessage());
        }
    }
}

Common Use Cases

1. Input Validation:

void setAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    this.age = age;
}

2. State Validation:

void withdraw(double amount) {
    if (balance < amount) {
        throw new IllegalStateException("Insufficient balance");
    }
    balance -= amount;
}

3. Null Check:

void setName(String name) {
    if (name == null) {
        throw new NullPointerException("Name cannot be null");
    }
    this.name = name;
}

Complete Example: Bank Account

class BankAccount {
    private String accountNumber;
    private double balance;

    BankAccount(String accountNumber, double initialBalance) {
        if (accountNumber == null || accountNumber.isEmpty()) {
            throw new IllegalArgumentException("Account number required");
        }
        if (initialBalance < 0) {
            throw new IllegalArgumentException("Balance cannot be negative");
        }
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }

    void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Amount must be positive");
        }
        balance += amount;
        System.out.println("Deposited: $" + amount);
    }

    void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Amount must be positive");
        }
        if (amount > balance) {
            throw new IllegalStateException("Insufficient balance");
        }
        balance -= amount;
        System.out.println("Withdrawn: $" + amount);
    }

    double getBalance() {
        return balance;
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            BankAccount account = new BankAccount("ACC001", 1000);
            account.deposit(500);
            account.withdraw(200);
            System.out.println("Balance: $" + account.getBalance());

            account.withdraw(2000);  // Will throw exception
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid argument: " + e.getMessage());
        } catch (IllegalStateException e) {
            System.out.println("Operation failed: " + e.getMessage());
        }
    }
}

Rules

  1. Checked exceptions must be declared with throws
  2. Unchecked exceptions don’t need declaration
  3. Can throw any Throwable object
  4. Use appropriate exception type
  5. Provide meaningful error messages

Quick Reference

// Throw unchecked
throw new ArithmeticException("Error message");

// Throw checked (must declare)
void method() throws IOException {
    throw new IOException("Error message");
}

// In constructor
MyClass(int value) {
    if (value < 0) {
        throw new IllegalArgumentException("Value must be positive");
    }
}

// In method
void validate(String input) {
    if (input == null) {
        throw new NullPointerException("Input cannot be null");
    }
}

Exam Tips

Remember:

  1. throw throws exception manually
  2. throws declares exception
  3. Syntax: throw new ExceptionType(“message”)
  4. Checked must declare with throws
  5. Unchecked no declaration needed
  6. Use for validation
  7. Provide meaningful messages
  8. Can re-throw caught exception
  9. Use appropriate exception type
  10. throw inside method body

Common Questions:

  • What is throw keyword?
  • throw vs throws?
  • How to throw exception?
  • Must we declare thrown exceptions?
  • When to throw exceptions?
  • Can we throw checked exceptions?
  • Re-throwing exceptions?
  • Common use cases?
  • Exception in constructor?
  • Best practices?