Gandalf StormCrow
Gandalf StormCrow

Reputation: 26192

Throwing custom exceptions in Java

Why do I need to wrap my thrown custom exceptions with try/catch whilst trying to throw them, but I don't have to do that for generic exceptions? Like in the example, my Exception subclass :

public class MyException extends Exception {
    public MyException(String msg) {
        super(msg);
    }
}

Throwing exceptions :

public class Exe {

    private static void testex(String test) {
        if (null!=test) {
            throw new UnsupportedAddressTypeException();
        } else {//Removing try/catch block results in compile failure
          try {
            throw new MyException("message");
          } catch (MyException e) {
            e.printStackTrace();
          }
        }
    }
}

Upvotes: 14

Views: 54872

Answers (4)

Ludwig Magnusson
Ludwig Magnusson

Reputation: 14379

If your exception extends java.lang.Exception, you must catch it (or rethrow). If it extends java.lang.RuntimeException, you are not required to do so. You will find that this is true for all standard exceptions as well.

edit Changed the words must not to not required to

Upvotes: 12

Jérôme Radix
Jérôme Radix

Reputation: 10533

From the Java Tutorial :

Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:

  • A try statement that catches the exception. The try must provide a handler for the exception, as described in Catching and Handling Exceptions.

  • A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception, as described in Specifying the Exceptions Thrown by a Method.

Code that fails to honor the Catch or Specify Requirement will not compile. Not all exceptions are subject to the Catch or Specify Requirement.

[...]

Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.

Upvotes: 0

Jonathan
Jonathan

Reputation: 859

UnsupportedAddressTypeException is a subclass of RuntimeException, and from the JavaDoc:

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

Upvotes: 17

andersoj
andersoj

Reputation: 22874

Your static method should declare

private static void testex(String test) throws MyException

if you want the method to throw it (and not to catch and handle it internally).

Upvotes: 7

Related Questions