Menu
Coddy logo textTech

Custom Exceptions

Part of the Logic & Flow section of Coddy's Java journey — lesson 43 of 59.

You can create your own exception class by extending the Exception class. This is useful when you need to handle specific types of errors in your application.

Here's how to create a custom exception:

public class AgeException extends Exception {
   public AgeException(String message) {
       super(message);
   }
}

And here's how to use it:

if (age < 0) {
   throw new AgeException("Invalid age: " + age);
}

After executing the above code with age = -5, the program throws:

AgeException: Invalid age: -5

challenge icon

Challenge

Easy

Create a custom exception class named EmailException and a method named validateEmail that takes one argument:

  1. A String (email) to validate

The method should throw your custom exception with these messages:

  • If email is null: "Email cannot be null"
  • If email is empty: "Email cannot be empty"
  • If email doesn't contain @: "Email must contain @"
  • If email doesn't contain any text before @: "Email must have a local part"
  • If validation passes: return "Valid email"

Cheat sheet

Create custom exceptions by extending the Exception class:

public class AgeException extends Exception {
   public AgeException(String message) {
       super(message);
   }
}

Throw custom exceptions using the throw keyword:

if (age < 0) {
   throw new AgeException("Invalid age: " + age);
}

Try it yourself

import java.util.Scanner;

class EmailException extends Exception {
    public EmailException(String message) {
        super(message);
    }
}

public class Main {
    public static String validateEmail(String email) throws EmailException {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String email = scanner.nextLine();
        if (email.equals("null")) {
            email = null;
        }
        
        try {
            System.out.println(validateEmail(email));
        } catch (EmailException e) {
            System.out.println(e.getMessage());
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow