Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write custom Exceptions?

Tags:

java

exception

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.

like image 384
Johanna Avatar asked Jul 01 '09 18:07

Johanna


People also ask

Can you write your own custom exception class?

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.

How do you define a custom exception type?

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.

What is custom exception explain it using example?

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.


2 Answers

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);     } } 
like image 88
jjnguy Avatar answered Oct 07 '22 16:10

jjnguy


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.
like image 35
toolkit Avatar answered Oct 07 '22 16:10

toolkit