Java Exceptions  «Prev  Next»

Lesson 6 Defining your own exception
ObjectiveDefine your own exception.

Defining Custom Exceptions

Often you will find it useful to define and throw your own exceptions, in addition to using the pre-defined Exception subclasses.
Here is an example of defining your own exception by simply subclassing Exception.

class MyException extends Exception { 
}

How do you create your own custom exceptions in Java?

In Java, you can create your own custom exceptions by creating a class that extends the Exception class or one of its subclasses, such as RuntimeException. Here's an example of how to create a custom exception class:
public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

In this example, the MyException class extends the Exception class, which makes it a checked exception. The class has a constructor that takes a message as a parameter, which is used to set the exception message.

To throw a custom exception, you can create an instance of the exception class and throw it using the throw keyword. Here's an example:
public void myMethod() throws MyException {
    if (someCondition) {
        throw new MyException("An error occurred.");
    }
}

In this example, the myMethod method checks for a condition and throws a MyException if the condition is true. The throws keyword is used to indicate that the method may throw a MyException. Custom exceptions can be useful when you need to handle specific error conditions that are not covered by built-in exceptions. By creating your own exception classes, you can provide more detailed error messages and handle errors in a more specific and controlled way.

Creating a Custom Checked Exception

You can subclass java.lang.Exception (or any of its subclasses) to define custom exceptions. To create custom checked exceptions, subclass java.lang.Exception or its subclasses (which are not subclasses of RuntimeException).
Let us revisit the exception classes in figure 5-6
Hierarchy of Exception and Error classes
Figure 5-6: Hierarchy of Exception and Error classes

A word of caution here: even though you can extend class java.lang.Throwable to create your own exceptions, it is not recommended. Class Throwable is the superclass of classes java.lang.Error and java.lang.Exception. The exception handler for this class will catch all types of errors and exceptions! For example, say an OutOf-MemoryError brings the JVM into an unstable state. Catching it as a subclass of Error or Throwable would be undesirable and potentially dangerous. Obviously, you may not want this behavior.
Note: Do not extend class java.lang.Throwable to create your own exceptions, even though you can. Class Throwable is the superclass of classes java.lang.Error and java.lang.Exception. The exception handler for this class will catch all types of errors and exceptions.

FileReader Constructor Exception

What will be the output of trying to compile and run the following piece of code? Assume that the file xyz.txt exists at the given location.
import java.io.*;
public class Test {
  public static void main(String [] args) {
    FileReader fr1 = new FileReader(new File("xyz.txt"));
    FileReader fr2 = new FileReader(new File("xyz.txt"));
    System.out.println(fr1.equals(fr2));
   }
}

  1. Compilation fails
  2. Compilation Succeeds but an Exception is thrown at runtime
  3. Compilation Succeeds and prints true at runtime
  4. Compilation Succeeds and print false at runtime

Answer: a
Explanation:
The FileReader constructor throws a FileNotFound Exception which is a checked exception. Since this exception is not handled or thrown by the main method, the compilation will fail.

Square Root Application - Exercise

In this exercise, you will modify SquareRoot so that it responds appropriately if the user inputs a negative number.
Square Root Application - Exercise