Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this sort of Java exception style bad practice?

Is it considered bad practice to have multiple try's in one method and structure the code like this?

public void whatever() {
   try {
     methodThatMayThrowIOException();
   } catch(IOException io) {
     // do something with exception here
   }

   // do more stuff here that won't throw exceptions

   try {
     methodThatMayThrowCustomException();
   } catch(CustomException ce) {
     // do something with custom exception here
   }
}
like image 994
Geo Avatar asked Feb 23 '10 08:02

Geo


People also ask

Is it bad practice to catch all exceptions?

Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly. The general principal is to catch the most specific type you can. catch(Exception) is a bad practice because it catches all RuntimeException (unchecked exception) too.

Is it bad to throw exception in Java?

The throws declaration is part of the method contract. You should always be as precise as possible when defining contracts. Saying throws Exception is therefore a bad idea. It's bad for the same reason it is bad practice to say a method returns an Object when it is guaranteed to return a String .

Is catching exception good to practice Java?

It is an essential concept never catch any exception so catch any exception only if you can handle it you can give additional contextual data in that exception. If you can't handle it in the catch block, then the best advice is don't catch it only to re-throw it.

Should you catch exceptions?

You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.


1 Answers

If the method can continue execution, without any problems even if the specified exception occurs this should be fine.

In the event where the exception should cause problems further down the line in the method, I would have it bubble up.

like image 70
Adriaan Stander Avatar answered Oct 01 '22 16:10

Adriaan Stander