Relax

Is it possible in Java to get rid of the need to catch RuntimeException ? Maybe compiler flags?

I know the reason the trap is moving forward, but I want to make simple and direct tools that ensure compliance with their requirements. Therefore, if something went wrong, I do not like to catch up, but to exit the application, breaking with a significant exception. This usually ends up like this:

 try { connection.close(); } catch (IOException e) { throw new RuntimeException(e); } 

which introduces 4 lines of code clutter and introduces a RuntimeException wrapper clutter on the error output. Sometimes it even motivates people to wrap large try ... catch (Throwable ..) blocks around anything, which is the likely reason for our favorite "Unknown error" warning boxes ...

+4
source share
6 answers

Is there any way in Java to get rid of the need to catch exceptions other than RuntimeException?

For a checked exception, you can choose between catching the exception and declaring it in the method header as a throw.

Maybe compiler flags?

No. There are no compiler flags for this. This is a fundamental part of language design. Loosening proven exception rules using the compiler switch will cause serious library compatibility issues.

+1
source

you can use the throws keyword with the prototype method to avoid the try-catch . which ultimately throws an exception for the JVM Default Exception handler, which stops the application if no catch block is specified in your code to handle the exception.

+3
source

An application crash at a glance at an exception is a very bad practice. Especially when some work is unsaved and the application uses some resources that need to be freed and cleaned up before the application completes execution. Some very popular software used for this ... and instead of "fixing" the problem, they introduced data recovery features when the application was restarted. However, the trick is not good software development.

At the very least, your application should not crash on the first error / error that occurred, but recover with a meaningful message. It's easy to just wrap everything in a RuntimeException (or even a Throwable ) and, especially, do nothing with it.

Java does not support flags of any type, because there are 1) a workaround and 2) the best ways to deal with this situation. For instance:

1. Handle the exception in the calling method

You can add the throws keyword to a method declaration, right down to your static public void main method, which, if it does not handle the exception, will ultimately crash the application using stacktrace.

 class Foo { public void someMethod(....) throws IllegalArgumentException, IOException { ... } static public void main(String...args) throws Throwable { new Foo().someMethod(); } } 

This method does not offer any means of recovery and is likely to make your user unhappy (with a big pointless stachtrace if they run the application from the console or just nothing if they run it from a shortcut or GUI). In addition, if you have some acquired resources, you cannot clear them when an exception occurs. At the very least, your main should catch (Throwable e) and output something before throwing the exception above. Sort of:

 class Foo { public void someMethod(....) throws IllegalArgumentException, IOException { ... } static public void main(String...args) { try { new Foo().someMethod(); } catch (...) { // output or log exception here and, optionally, cleanup and exit } } } 

** EDIT **

Consider this scenario: the program initializes some resource to process some data, then during processing there is some exception (or error) at runtime, the application crashes, but the resources are not freed or not freed. However, in Java this can be done.

 public E doSomething() throws RuntimeException { // declare a bunch of resources try { // process resources with unchecked exceptions } finally { // free resources } // return some result } 

and cleanly exit the method on error or on successful completion, possibly even registering a runtime error for the "offspring".

2. Write down the error and return some meaningful value

Registration is a very good practice. You can show your user some message telling them that the operation cannot be completed without failures, and gives you some traces of what and where the user is doing. A simplified registration system can be:

 class Foo { static private final Logger LOG = Logger.getLogger(Foo.class.getName()); public boolean doSomethingImpl(...) { boolean result = true; try { ... } catch (SomeException e) { LOG.log(Level.SEVERE, "meaningful message why method could not do something!", e); result = false; } return result; } public void doSomething() { if (!doSomethingImpl(...)) { // handle failure here } } } 

By default, Logger outputs everything to err output, but you can add your own custom handlers:

 // loggers are singletons, so you can retrieve any logger at anytime from // anywhere, as long as you know the logger name Logger logger = Logger.getLogger(Foo.class.getName()); logger.setUseParentHandlers(false); // disable output to err logger.addHandler(new MyHandler()); // MyHandler extends java.util.logging.Handler 

Java already comes with some default registration handlers, one of which writes to a file .

and etc.

+3
source

I do not think there is any way for the JVM. It is best that your methods re-select an exception that gets rid of the โ€œclutterโ€ in your code, and then your main program throws an exception. This should spread the error all the way to the top of your program.

Keep in mind, however, that the place where the exception actually occurs is much better at letting the user know what happened (i.e. exactly what he was doing when this particular IOException event occurred). You will lose this permission if all errors are simply spread to the top level.

+1
source

You have the opportunity to throw your exceptions to the level. Here is an example

 public class Foo { public Foo() { super(); } public void disconnect(connection) throws IOException { connection.close(); } } 
+1
source

Use "Throws" to avoid a mistake ... but it will not be good practice programimg

+1
source

All Articles