Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, when should I create a checked exception, and when should it be a runtime exception? [duplicate]

Tags:

java

exception

Possible Duplicate:
When to choose checked and unchecked exceptions

When should I create a checked exception, and when should I make a runtime exception?

For example, suppose I created the following class:

public class Account {     private float balance;      /* ... constructor, getter, and other fields and methods */      public void transferTo(Account other, float amount) {         if (amount > balance)             throw new NotEnoughBalanceException();         /* ... */     } } 

How should I create my NotEnoughBalanceException? Should it extend Exception or RuntimeException? Or should I just use IllegalArgumentException instead?

like image 730
Hosam Aly Avatar asked Jan 31 '09 19:01

Hosam Aly


People also ask

When should a checked exception be created?

Checked exceptions are exceptions that need to be treated explicitly. The code above is a classic way of handling Java checked exceptions. While the code throws FileNotFoundException, it's not clear what the exact cause is — whether the file doesn't exist or the file name is invalid.

When should we use checked exceptions in Java?

“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.” In this way, we can recover the system by accepting another user input file name.

When should you use runtime exception?

RuntimeException is used for errors when your application can not recover. For example, NullPointerException and ArrayOutOfBoundsException. You can avoid a RuntimeException with an 'if' command. You should not handle or catch it.

What's the difference between a runtime exception and a checked exception?

A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled. A runtime exception is a programming error and is fatal whereas a checked exception is an exception condition within your code's logic and can be recovered or re-tried from.


2 Answers

There's a LOT of disagreement on this topic. At my last job, we ran into some real issues with Runtime exceptions being forgotten until they showed up in production (on agedwards.com), so we resolved to use checked exceptions exclusively.

At my current job, I find that there are many who are for Runtime exceptions in many or all cases.

Here's what I think: Using CheckedExceptions, I am forced at compile time to at least acknowledge the exception in the caller. With Runtime exceptions, I am not forced to by the compiler, but can write a unit test that makes me deal with it. Since I still believe that the earlier a bug is caught the cheaper it is to fix it, I prefer CheckedExceptions for this reason.

From a philosophical point of view, a method call is a contract to some degree between the caller and the called. Since the compiler enforces the types of parameters that are passed in, it seems symmetrical to let it enforce the types on the way out. That is, return values or exceptions.

My experience tells me that I get higher quality, that is, code that JUST WORKS, when I'm using checked exceptions. Checked exceptions may clutter code, but there are techniques to deal with this. I like to translate exceptions when passing a layer boundary. For example, if I'm passing up from my persistence layer, I would like to convert an SQL exception to a persistence exception, since the next layer up shouldn't care that I'm persisting to a SQL database, but will want to know if something could not be persisted. Another technique I use is to create a simple hierarchy of exceptions. This lets me write cleaner code one layer up, since I can catch the superclass, and only deal with the individual subclasses when it really matters.

like image 58
Don Branson Avatar answered Oct 19 '22 09:10

Don Branson


In general, I think the advice by Joshua Bloch in Effective Java best summarises the answer to your question: Use checked expections for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition).

So in this case, if you really want to use exceptions, it should be a checked one. (Unless the documentation of transferTo() made it very clear that the method must not be called without checking for sufficient balance first by using some other Account method - but this would seem a bit awkward.)

But also note Items 59: Avoid unnecessary use of checked exceptions and 57: Use exceptions only for exceptional conditions. As others have pointed out, this case may not warrant an exception at all. Consider returning false (or perhaps a status object with details about what happened) if there is not enough credit.

like image 40
Jonik Avatar answered Oct 19 '22 08:10

Jonik