153

How do we create custom exceptions in Java?

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Suresh
  • 38,717
  • 16
  • 62
  • 66
  • 2
    It's the same methodology used in most OO languages: extend the base Exception class. – NDM Nov 18 '09 at 08:08
  • 2
    Check out http://stackoverflow.com/questions/1070590/how-can-i-write-an-exception-by-myself – demongolem May 09 '14 at 14:56
  • 1) // Class that represents use-defined expception class MyException extends Exception { public MyException(String s) { super(s); } } ------------------------------------------------ 2) try { // Throw an object of user defined exception throw new MyException("TestException"); } catch (MyException ex) { System.out.println("Caught"); // Print the message from MyException object System.out.println(ex.getMessage()); } – Mandeep Yadav Jun 30 '18 at 17:21

3 Answers3

291

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.

Solomon Ucko
  • 5,724
  • 3
  • 24
  • 45
Adamski
  • 54,009
  • 15
  • 113
  • 152
24
public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}
laura
  • 7,280
  • 4
  • 35
  • 43
4

For a checked exception:

public class MyCustomException extends Exception { }

Technically, anything that extends Throwable can be an thrown, but exceptions are generally extensions of the Exception class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Errors which usually are not something designed to be gracefully handled beyond the JVM internals.

You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.

As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via

throw new MyCustomException()

and catch via

catch (MyCustomException e) { }
Amber
  • 507,862
  • 82
  • 626
  • 550
  • 4
    RuntimeException extends Exception and is not a checked exception. – Adamski Nov 18 '09 at 08:21
  • 2
    Technically, anything that extends `Throwable` can be *thrown*; exceptions extend `Exception`. A custom subclass of Throwable would not be caught by a `try { ... } catch (Exception e) { ... }` block. – Andrzej Doyle Nov 18 '09 at 08:35
  • Why are people upvoting this answer? It contains a few inaccuracies. 1) You cannot *implmenet* throwable as it's an interface. 2) Anything that *extends* Throwable is **NOT** an exception (`Error` is not an exception, it's an error). 3) It implies that any subclass of Exception is checked whereas RuntimeException is not. The answer given by Adamski is much more accurate! – oxbow_lakes Nov 18 '09 at 09:35
  • Oops - I meant throwable is **not** an interface of course! – oxbow_lakes Nov 18 '09 at 09:37
  • @oxbow_lakes - the ideal solution would be to fix the inaccuracies, no? Anyhow, I've corrected them myself since no one else did. – Amber Nov 18 '09 at 10:51