When do I need to intercept RuntimeExceptions in code?

During programming in java, is there any time that I, as a programmer, have to consider in order to catch RuntimeExceptions?

+6
source share
5 answers

You get a RuntimeException for the same reason that you catch any exception: you plan to do something about it. Perhaps you can fix everything that caused the exception. You might just want to reconstruct with a different type of exception.

The trick and ignoring of any exceptions, however, is extremely bad practice.

+8
source

This is what I can think of.

  • If you want to show the perfect message to the end user, if something went wrong, get a RuntimeException and write it down. Then show a good message on the screen instead of an explosion error.
  • To wrap specific CheckedExceptions for specific RuntimeExceptions applications. It is preferable to use a RuntimeException as its usual exception, as indicated here .
+2
source

Based on a user check, if you want to show a custom message to the user, go to a RuntimeException .

Wrap your own message and then throw it away.

 throw new RuntimeException("Invalid userName/Password !"); 
0
source

Basically, the only time you want to catch it is when you cannot let your application explode. This is a good article that describes it in much more detail, but here is a quote that summarizes it:

 "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". 

Since unchecked exceptions are mostly bugs in your code and really should only be thrown where nothing can be done about them, the only real moment when you want to catch it is when you cannot let your application explode.

0
source

Yes: whenever you can and want to restore them.

Many common exceptions inherit from RuntimeException , and each may or may not be RuntimeException depending on the specific circumstances. The RuntimeException class RuntimeException does not mean that the exception should or should not be caught.

For example, you might have a library method that throws an IllegalArgumentException on specific inputs. If this applies to your program, you can catch this exception and somehow restore it, for example, by trying another input or explaining to the user why the operation cannot continue.

-1
source

Source: https://habr.com/ru/post/920599/


All Articles