Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using exception classes to model errors

Tags:

java

oop

I want to know whether it would be right to use exception classes as regular classes to handle application errors (just regular controlled errors, not exceptional ones), without throwing them with the proper language clause (eg. instantiating them and returning them from a method). I've been discussing this topic recently with some colleges and I think that exceptions should only be used as exceptions, but I'd like to listen to more opinions.

like image 864
beni0888 Avatar asked Feb 05 '26 05:02

beni0888


1 Answers

What you mean by "controlled error" is actually known by the name checked exception.

"Exceptional exceptions" are known as unchecked exceptions.

The difference is explained here: Checked vs Unchecked exception

So, you see: Java comes with a built-in mechanism to distinguish between

  • exceptions caused by programming mistakes (e.g. NullPointerException when passing unexpected null as an argument) -- unchecked exceptions
  • versus anticipated exceptions that should be handled by the caller (e.g. IOException when some kind of I/O went wrong) -- checked exceptions

Returning instances of Exception (or any subclass) would be considered a misuse in virtually all circumstances.


You could ask your colleague how he/she would implement an exceptional outcome of a method with this signature:

public String createStringOrFailWithException();

Returning an Exception? Certainly not, because this requires a different return type.

Throwing the exception instead allows you to keep the return type, and to benefit from vast exception handling capabilities, including finally blocks and try-with-resources statements, to give only two examples that you don't want (should not) implement by yourself.

like image 120
Philipp Merkle Avatar answered Feb 07 '26 17:02

Philipp Merkle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!