user3803797 user3803797 - 1 year ago 61
Java Question

Throw exceptions without needing to use try in Java

I have this Java code that i want to be able to run. It should throw an exception if it have totally been added more than 4 strings, but it should not be needed to use a try/catch the first 4 times the addString method is called.

Foo myFoo = new Foo();
myFoo.addString("String A");
myFoo.addString("String B");
myFoo.addString("String C");
myFoo.addString("String D");

boolean exceptionThrown = false;

try {
myFoo.addString("String E");
} catch (NoRoomForMoreStringsException e) {
exceptionThrown = true;


If i add something like this in the addString function, it will require me to always use a trow/catch statement.

public void addString(String str) throws NoRoomForMoreStringsException {
if(strings.size() >= 4) {
throw new NoRoomForMoreStringsException();

How can i throw an exception in the addString method without needing to always use the try/catch statement?

Answer Source

How can i throw an exception in the addString method without needing to always use the try/catch statement ?

You need to declare NoRoomForMoreStringsException as RuntimeException as shown below:

public NoRoomForMoreStringsException extends RuntimeException {

   //methods for custom exception

In Java, Exception objects are two types:

(1) Checked Exceptions: These exceptions force you to try/catch or declare them in method signature (like your current NoRoomForMoreStringsException). The best practice is you need to use these Checked exceptions very carefully i.e., only when you have got a recovery action that needs to be done upon catching the exception.

(2) Unchecked/Runtime Exceptions (Preferred) : These exceptions don't force you to catch or declare the exception.

Most of the times, you can prefer using Runtime Exceptions (Type 2 above) because in general, we will be able to do very little (like logging) upon getting an exception.

Because Checked Exceptions are very noisy (means they force the callers either to catch or declare in method signatures), popular frameworks (like Spring) try to avoid them i.e., Spring throws Runtime Exceptions or even better wraps/converts the Checked Exceptions (if any from JDK) into Runtime Exceptions and then throws.

So, in short, if you have got a recovery mechanism, you will go for Checked Exception (Type1 above), otherwise, you need to go for RuntimeException (Type2 above)

You can refer here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download