Unlock Your Python Backend Career: Build 30 Projects in 30 Days. Join now for just $54

Error handling in Java

Java Backend Development: Zero to Hero

Error handling in Java

Exception Handling in java (throw & throws)

Exception Handling in java (throw & throws)

throw

  • The throw keyword is used to explicitly throw an exception. By default, all predefined exceptions in Java are created and thrown implicitly. If we want to throw an exception manually, we use the throw keyword.

  • We can throw either checked or unchecked exceptions using throw.

  • When throw is executed, the method terminates immediately, and further code is not executed.

  • We must create a new exception object using throw new ExceptionType(...).

  • Only objects of classes that extend Throwable (or its subclasses) can be thrown.

image (36).pngSyntax

throw new ExceptionType("Error message");

Example

public class Mastering_backend {
    public static void main(String[] args) {
        int age = 15;
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or above");
        }
        System.out.println("You are eligible to vote.");
    }
}

In this example, we explicitly throw an IllegalArgumentException if the age is less than 18.

Output

Exception in thread "main" java.lang.IllegalArgumentException: Age must be 18 or above
	at Main.main(Main.java:5)

throws

  • The throws keyword in Java is used to declare exceptions that a method might throw.

  • It specifies a list of exceptions that can be thrown during the execution of the method.

image (37).pngSyntax

returnType methodName(parameters) throws ExceptionType1, ExceptionType2 {
    // method body
}
public void readFile() throws IOException {
    // code that might throw IOException
}
public void processFile() throws IOException, ParseException {
    // code that might throw either IOException or ParseException
}

Example

import java.io.IOException;

public class MasteringBackend {

    // Method that declares it might throw an IOException
    public static void readFile(String fileName) throws IOException {
        if (fileName == null || fileName.isEmpty()) {
            // Throwing a checked exception
            throw new IOException("File name cannot be empty");
        }
        System.out.println("Reading file: " + fileName);
    }

    // Method that throws an unchecked exception
    public static void validateAge(int age) {
        if (age < 18) {
            // Throwing an unchecked exception (no need to declare with throws)
            throw new IllegalArgumentException("Age must be 18 or above");
        }
        System.out.println("Age is valid for access.");
    }

    public static void main(String[] args) {
        System.out.println("== Mastering Backend ==");

        // Example 1: Handling checked exception using try-catch
        try {
            readFile(""); // Will throw IOException
        } catch (IOException e) {
            System.out.println("Caught IOException: " + e.getMessage());
        }

        // Example 2: Unchecked exception (optional to handle, but can crash if not caught)
        try {
            validateAge(15); // Will throw IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.out.println("Caught IllegalArgumentException: " + e.getMessage());
        }

        System.out.println("Program ended successfully.");
    }
}

In this example, the throws keyword is used in the method signature to declare checked exceptions like IOException, while unchecked exceptions like IllegalArgumentException do not need to be declared with throws.

Output

== Mastering Backend ==
Caught IOException: File name cannot be empty
Caught IllegalArgumentException: Age must be 18 or above
Program ended successfully.

throw vs throws

  • throw – The throw keyword is used to actually throw an exception.

  • throws – The throws keyword is used to declare a list of exceptions that a method might throw.

throw

throws

throw is used when you actually want to throw an exception, like saying “There’s a problem, stop right here!”

throws is used to warn that a method might cause a problem, like saying “This method may throw an exception, be ready for it.”

After throw, you must give a specific exception object (like new IOException("msg")).

After throws, you just list the possible exception types (like throws IOException, SQLException).

You write throw inside the method body.

You write throws in the method signature, next to the method name.

You can only throw one exception at a time with throw.

You can declare multiple exceptions separated by commas with throws.

Example:

// Using throws
public void readFile() throws IOException, SQLException {
    // Inside this method, you can use throw
    throw new IOException("File not found");
}

In this example, throw is used to throw an exception (new IOException("File not found")), and throws is used to declare that the method may throw that exception.

User Defined exception

A user-defined exception is a custom exception created by the programmer by extending the Exception class (for checked exceptions) or RuntimeException class (for unchecked exceptions).

Syntax

// For a checked exception
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

// For an unchecked exception
class MyRuntimeException extends RuntimeException {
    public MyRuntimeException(String message) {
        super(message);
    }
}

Example

// Custom exception class
class InvalidBookingException extends Exception {
    public InvalidBookingException(String message) {
        super(message);
    }
}

public class MasteringBackend {
    public static void bookSeat(int seatNumber) throws InvalidBookingException {
        if (seatNumber <= 0 || seatNumber > 100) {
            throw new InvalidBookingException("Seat number " + seatNumber + " is invalid!");
        }
        System.out.println("Seat " + seatNumber + " booked successfully.");
    }

    public static void main(String[] args) {
        try {
            bookSeat(105);
        } catch (InvalidBookingException e) {
            System.out.println("Booking failed: " + e.getMessage());
        }
    }
}

In this example, we created a custom exception by extending the Exception class, named InvalidBookingException.

Output

Booking failed: Seat number 105 is invalid!

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board