Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Exception vs. rolling your own exception

At what point would you create your own exception class vs. using java.lang.Exception? (All the time? Only if it will be used outside the package? Only if it must contain advanced logic? etc...)

like image 875
mcjabberz Avatar asked Oct 26 '08 04:10

mcjabberz


People also ask

What is the difference between Java Lang exception and Java Lang RuntimeException classes?

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile.

Why do we need Java Lang exception?

This is an IllegalAccessException is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.

Why would you need to write your own exception?

Custom exceptions provide you the flexibility to add attributes and methods that are not part of a standard Java exception. These can store additional information, like an application-specific error code, or provide utility methods that can be used to handle or present the exception to a user.

Can I throw my own exception in Java?

You can create your own exceptions in Java. All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.


1 Answers

I think you need to ask yourself a slighly different question "What advantage does creating a new exception give me or developers who use my code?" Really the only advantage it gives you or other people is the ability to handle the exception. That seems like an obvious answer but really it's not. You should only be handling exceptions that you can reasonably recover from. If the exception you throw is a truly fatal error why give developers a chance to mis-handle it?

More in depth discussion: Custom exceptions: When should you create them?

like image 192
JaredPar Avatar answered Sep 28 '22 10:09

JaredPar