noob
noob

Reputation: 623

How to create checked/unchecked custom exceptions in Java?

When I create my own exceptions, is it possible to mark them as being checked/unchecked? (using some annotation, maybe?) Or, is extending Exception/RuntimeException the only way of doing it?

Thanks.

Upvotes: 29

Views: 36600

Answers (2)

SM ANSARI
SM ANSARI

Reputation: 395

Checked Exception

By extending Exception, you can create a checked exception:

class NotEnoughBalance extends Exception {
     // Implementation
}

Unchecked Exception

By extending RuntimeException, you can create unchecked exception:

class NotEnoughBalance extends RuntimeException {
     // Implementation
}

Upvotes: 21

GaryF
GaryF

Reputation: 24370

The only way of doing it is to extend Exception (or a subclass thereof) for a checked exception, and extending RuntimeException (or a subclass thereof) for an unchecked exception.

Given how lightweight it is to do that, and the benefits you get from extending those classes, I don't think that's too onerous.

Upvotes: 42

Related Questions