5. Exception Handling
Programming Project 2022/23

5.5. Custom Exceptions

Creating new exception types

Any custom exception or error we create must extend Throwable or one of its subclasses.

By convention, we add one of the two suffixes to our custom exception types

  • Exception
  • Error

and get, for example, the following.

  • InvalidMessageException
  • SuperDarkError

Typically, we declare four constructors for a custom exception type.

  • no parameters
  • string parameters
  • string and throwable parameters
  • throwable parameter

Whenever possible, extend a more specific exception class.

  • IOException
  • ArithmeticException

Otherwise, decide whether your class should represent checked or unchecked exceptions.

  • If users should be required to handle it, extend Exception.
  • If users should not be required to handle it, extend RuntimeException.

Here is an example of a simple custom exception.

public class MyException extends Throwable {
  public MyException() {}

  public MyException(String message) {
    super(message);
  }

  public MyException(String message, Throwable cause) {
    super(message, cause);
  }

  public MyException(Throwable cause) {
    super(cause);
  }

  @Override
  public String getMessage() {
    return "This is my own exception";
  }
}
public class Main {

  public static void main(String[] args) {
    try {
      throwMyException();
    } catch (MyException e) {
      e.printStackTrace();
    }
  }

  public static void throwMyException() throws MyException {
    throw new MyException();
  }

}

Exercise 3

  1. Write a custom exception class called WrongFileExtension that
  • contains constructors that accept a String parameter containing a file extension and
  • overrides the getMessage() method to return a custom message.
  1. Write a class main method that reads a file extension from the console using the snippet below.
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter an file format: ");
    String extension = scanner.nextLine();
  2. If the provided file extension is not equal to json, xml, or csv, throw a WrongFileExtension.

You can find the solution to this exercise here.