Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing custom exceptions in Java

Tags:

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();
          }
        }
    }
}
like image 554
Gandalf StormCrow Avatar asked May 13 '12 20:05

Gandalf StormCrow


People also ask

Can we throw custom exception in Java?

In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.

Can we use throws for custom exception?

The throw keyword is useful for throwing exceptions based on certain conditions e.g. if a user enters incorrect data. It is also useful for throwing custom exceptions specific to a program or application. Unchecked exceptions can be propagated in the call stack using the throw keyword in a method.

When a programmer throw an custom exception he must declare?

Using throws keyword we can declare the method which might be exception producing. In order to use a custom exception, you must show classes that call your code that they need to plan for this new type of exception. You do this by declaring that one or more of your methods throws the exception.


3 Answers

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.

like image 124
Jonathan Avatar answered Oct 18 '22 19:10

Jonathan


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

like image 20
Ludwig Magnusson Avatar answered Oct 18 '22 18:10

Ludwig Magnusson


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).

like image 7
andersoj Avatar answered Oct 18 '22 20:10

andersoj