I have a Custom exception class which extends Exception class (like below).
public class SomeABCException extends Exception
But, when I use this SomeABCException
in all places where I previously used Exception
in the catch block, it does not catch the Exceptions even after it extends Exception
class itself.
E.g. if a parent/caller method has a catch block as below
catch (Exception e) {
TODO something;
}
and if I have a child method as below in which I am running some database queries.
try {
Some database queries;
} catch (SomeABCException e) {
throw new SomeABCException (e.getMessage(),"I/O or SQL_EXCEPTION");
}
Here if the sql connection fails, the catch is not able to catch the exceptions, rather it gets caught in the parent/callers catch block which uses System.Exception to catch it.
During the debug, it does not go to the throw in the catch block on child method.
Please explain, I do not understand it.
The custom exception should extends RuntimeException if you want to make it unchecked else extend it with Exception. With unchecked exceptions calling code method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword.
You can throw it in your code and catch it in a catch clause. And you can but don't need to specify if your method throws it.
Basically, Java custom exceptions are used to customize the exception according to user need. Consider the example 1 in which InvalidAgeException class extends the Exception class. Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e.
I believe you are thinking backwards. Instances of Exception
will only catch exceptions that are subclasses, or instances of it. So, since Exception
is a superclass of SomeABCException
, the SQLException
will NOT be caught.
Try this instead:
try {
//Some database queries; -> this will throw Exception
} catch (Exception e) {
throw new SomeABCException (e.getMessage(),"I/O or SQL_EXCEPTION");
}
You are catching SomeABCException
when your "some database queries" are not throwing that kind of exception (maybe some SQLException
or something like that)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With