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.
Whenever possible, extend a more specific exception class.
IOException
ArithmeticException
Otherwise, decide whether your class should represent checked or unchecked exceptions.
Exception
.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();
}
}
WrongFileExtension
that
String
parameter
containing a file extension andgetMessage()
method to return a custom message.
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter an file format: ");
String extension = scanner.nextLine();
json
, xml
, or csv
, throw a WrongFileExtension
.You can find the solution to this exercise here.