How can I create a new Exception
different from the pre-made types?
public class InvalidBankFeeAmountException extends Exception{ public InvalidBankFeeAmountException(String message){ super(message); } }
It will show the warning for the InvalidBankFeeAmountException which is written in the first line.
To create a custom exception, we have to extend the java. lang. Exception class. Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.
In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this 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. Consider the example 1 in which InvalidAgeException class extends the Exception class.
All you need to do is create a new class
and have it extend Exception
.
If you want an Exception
that is unchecked, you need to extend RuntimeException
.
Note: A checked Exception
is one that requires you to either surround the Exception
in a try
/catch
block or have a 'throws
' clause on the method declaration. (like IOException
) Unchecked Exceptions
may be thrown just like checked Exceptions
, but you aren't required to explicitly handle them in any way (IndexOutOfBoundsException
).
For example:
public class MyNewException extends RuntimeException { public MyNewException(){ super(); } public MyNewException(String message){ super(message); } }
just extend either
Exception
, if you want your exception to be checked (i.e: required in a throws clause)RuntimeException
, if you want your exception to be unchecked.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