James Raitsev
James Raitsev

Reputation: 96491

Is it possible to create my own unchecked Exception in Java?

Is it possible to create my own unchecked exception in Java?

Basically, I'd like to

Upvotes: 23

Views: 20544

Answers (5)

Diogo Capela
Diogo Capela

Reputation: 6590

I'll leave an example here, just in case:

public class MyCustomException extends RuntimeException {

    public MyCustomException(String message) {
        super(message);
    }

}

Upvotes: 1

vinS
vinS

Reputation: 1475

YES. According to Effective Java -

While the Java Language Specification does not require it, there is a strong convention that errors are reserved for use by the JVM to indicate resource deficiencies, invariant failures, or other conditions that make it impossible to continue execution. Given the almost universal acceptance of this convention, it’s best not to implement any new Error subclasses. Therefore, all of the unchecked throwables you implement should subclass RuntimeException (directly or indirectly).

Below usage of unchecked exception is recommended :-

  1. Use runtime exceptions to indicate programming errors.
  2. If you believe a condition is likely to allow for recovery, use a checked exception; if not, use a runtime exception. If it isn’t clear whether recovery is possible, you’re probably better off using an unchecked exception.

About documenting unchecked exception -

Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

Yes - derive it from RuntimeException

Make sure that you do it for the right reason: as a rule, runtime exceptions indicate programming errors, rather than errors that a program could potentially react to in some meaningful way.

Upvotes: 5

Corbin
Corbin

Reputation: 33457

I think you're just wanting to subclass RuntimeException?

Upvotes: 2

Aravind Yarram
Aravind Yarram

Reputation: 80194

Yes. Extend MyUncheckedException from RuntimeException. However, below is the guideline from documentation

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Upvotes: 36

Related Questions