-2

Most of the time, if I want to terminate the execution of the program at a certain critical point, I just create a RuntimeException with some informational messages:

throw new RuntimeException("ERROR: this is wrong! Fix it first!")

In Java there are lots of different built-in exception types, and books also teach how to create your own custom exception types. Is that really necessary? Isn't a RuntimeException sufficient for most purposes from a practical point point of view?

user697911
  • 10,043
  • 25
  • 95
  • 169

3 Answers3

2

Most of the time, if I want to terminate the execution of the program at a certain critical point

Most of the time I don't want to terminate my application but I want to recover from exception to continue execution.

In general, you dont have to define your own exceptions as you could (technically) use only eg. Exception and RuntimeException but creating your own exception classes allowes you to fine graing catching of such exceptions. For example

try{
   myService.doSomething();
}catch(MyCustomException){
 //handle custom exception here- eg.
  retunr Constants.DEFAULT_RESPONSE;
}catch(RuntimeException e){
  log.error("Unknown Error",e);
  return null;
}

So in this scenario I allow myself to recover from exception thrown by my service method but in the same time I am loggin all others exceptions (returning null is not hte best practice what so ever)

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
1

I strongly discourage the use of generic RuntimeException and Exception. This is to allow us to be able to handle different exceptions in different ways.

For example, if I catch a RuntimeException, I would want to do a different action if it's due to bad input (so we can tell the user to fix their input), a disk error (so we can alert the operations team so they can replace), or a null pointer (which is clearly a bug). Throwing and catching generic RuntimeExceptions make this more difficult than is really necessary.

Joe C
  • 15,324
  • 8
  • 38
  • 50
  • As I think that what you have in mind, I disagree with stance to not to use RunitimeExceptions. To me it is a common practice to eg. wrap ungandled exceptions into RuntimeExceptions and rethrow. – Antoniossss Oct 31 '18 at 23:27
0

One way having different types of exceptions is useful is that you can define how your program should behave in response to a particular exception being thrown.

try {
    // code that may throw several types of exceptions
} catch (Exception1 e) {
    // handle Exception1
} catch (Exception2 e) {
    // handle Exception2
} catch ...

In this way a running program may recover from an exception and may continue running.