What class should you extend in order to create your own exception that you can throw?
Java has many built-in exception classes, such as Show
I am designing a custom Exception class for my application. I have a very basic question. Should I extend from Exception class or Thowable class ? What are the benefits ? I intend to throw this from underlying layers and catch it in the top level classes. Will it influence my decision of using Thowable over Exception. Is it fundamentally right to catch a Thowable ? I 've gone through some other threads in this forum. They talk about having the stack trace maintained when it is thrown and not having it for exception etc. I understand that some say ( here) that Thowable is super class of Exception and we should not use it. But others (here) say Exception is for "Exceptional " cases. This question is rather a discussion of how one is better than other rather than asking how.
asked Feb 15, 2013 at 9:34
2
Exceptions come in 2 flavours:
If you want the users of your code, to explicitely handle some exceptional
situations, it would be good to just extend answered Feb 15, 2013 at 9:49
Ostap AndrusivOstap Andrusiv 4,7071 gold badge35 silver badges38 bronze badges
Like But it is not advisable, according to the following doc:
Keeping this concept in mind, I would suggest to extend answered Feb 15, 2013 at 9:51
RASRAS 8,04516 gold badges64 silver badges86 bronze badges 0 Fundamentally you should extends answered Feb 15, 2013 at 9:40
Can exception class be extended?The class extends the Exception class that is defined in the Java core API (in the package is java. lang ). When extending Exception you are defining a "checked" exception, i.e., an exception that must be caught or thrown. A constructor is provided that passes the message argument to the super class Exception .
How do you create and throw exception?We can also define our own set of conditions and throw an exception explicitly using throw keyword. For example, we can throw ArithmeticException if we divide a number by another number. Here, we just need to set the condition and throw exception using throw keyword. The syntax of the Java throw keyword is given below.
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.
What exception can be to throw Java?There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.
|