Why do I need to wrap my thrown custom exceptions with try
/catch
whilst trying to throw them, but I don't have to do that for generic exceptions? Like in the example, my Exception
subclass :
public class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
Throwing exceptions :
public class Exe {
private static void testex(String test) {
if (null!=test) {
throw new UnsupportedAddressTypeException();
} else {//Removing try/catch block results in compile failure
try {
throw new MyException("message");
} catch (MyException e) {
e.printStackTrace();
}
}
}
}
In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user need.
The throw keyword is useful for throwing exceptions based on certain conditions e.g. if a user enters incorrect data. It is also useful for throwing custom exceptions specific to a program or application. Unchecked exceptions can be propagated in the call stack using the throw keyword in a method.
Using throws keyword we can declare the method which might be exception producing. In order to use a custom exception, you must show classes that call your code that they need to plan for this new type of exception. You do this by declaring that one or more of your methods throws the exception.
UnsupportedAddressTypeException is a subclass of RuntimeException, and from the JavaDoc:
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
A 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.
If your exception extends java.lang.Exception, you must catch it (or rethrow). If it extends java.lang.RuntimeException, you are not required to do so. You will find that this is true for all standard exceptions as well.
edit Changed the words must not to not required to
Your static method should declare
private static void testex(String test) throws MyException
if you want the method to throw it (and not to catch and handle it internally).
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