0

I know that to create a new exception, I must make a subclass of the Java Exception class.

public class MyOwnException extends Exception
{
     /*ok, what goes here? where do we tell java when to throw this exception
       and what to print out when this exception is thrown?*/
}
BarrySW19
  • 3,759
  • 12
  • 26
Steven Zhao
  • 301
  • 1
  • 2
  • 8
  • possible duplicate of [How to define custom exception class in Java, the easiest way?](http://stackoverflow.com/questions/3776327/how-to-define-custom-exception-class-in-java-the-easiest-way) – BartoszKP Nov 12 '14 at 22:49
  • possible duplicate too : http://stackoverflow.com/questions/1070590/how-can-i-write-an-exception-by-myself – Vincent D. Nov 12 '14 at 22:50
  • use `throw new MyOwnException("message");` create a constructor – Vincent D. Nov 12 '14 at 22:52

1 Answers1

4

The only thing that is required from your exception is the ability for it to be thrown. Briefly said, you can throw everything that inherits from java.lang.Throwable class. You should, however, inherit your exceptions from java.lang.Exception class. If you define your exception like this:

public class MyException extends Exception
{
}

it is a completely valid exception which can be thrown:

throw new MyException();

and which carries a stack trace with it. This stack trace gets printed (along with the exception type) if the exception is not caught and leaves your main function. There is no special specification of what the exception does when not caught.

However, it is usually better for your exception class to implement at least constructors taking string message and another Exception, simply calling super constructors with same arguments. This way you can add messages to your exception instances and wrap other exceptions in it.

Ips
  • 369
  • 1
  • 6
  • 1
    "*Stacktrace will be printed if not caught*" - This might throw people off. Anything that extends `Exception` ***must*** be caught (or thrown), unless it's a subclass of `RuntimeException`, as stated in the [doc](https://docs.oracle.com/javase/7/docs/api/java/lang/Exception.html). You should then call `printStackTrace()` manually in the catch block (if you choose to catch the `Exception` rather than throw it). Other than that, +1 – Vince Nov 12 '14 at 23:48