154

How do we create custom exceptions in Java?

3
  • 2
    It's the same methodology used in most OO languages: extend the base Exception class. Commented Nov 18, 2009 at 8:08
  • 2
    Check out stackoverflow.com/questions/1070590/… Commented May 9, 2014 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()); } Commented Jun 30, 2018 at 17:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

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) { }

5 Comments

RuntimeException extends Exception and is not a checked exception.
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.
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!
Oops - I meant throwable is not an interface of course!
@oxbow_lakes - the ideal solution would be to fix the inaccuracies, no? Anyhow, I've corrected them myself since no one else did.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.