Sometimes for our programming requirements, we need to create our exceptions, such types of exceptions are known as user-defined exceptions or customized exceptions.
For Example-
If the user is less than 18, the user is not illegal for voting, so we can create our exception NotAllowedException
.
package UserDefine;
import java.util.Scanner;
class NotAllowedException extends RuntimeException
{
NotAllowedException(String e){
System.out.println(e);
}
}
public class UserDefinedException{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age");
int age = sc.nextInt();
if(age<18){
throw new NotAllowedException(" You're not eligible for voting");
}
else {
System.out.println("You're eligible for voting");
}
}
}
Note-
- Throw keyword is best suitable for user-defined or customized exceptions.
- It is highly recommended to define customized exceptions as unchecked exceptions that is we have to extend RunTimeException
Similar Java Tutorials
- Odd Even in Java
- Fibonacci Series Java
- Data Hiding in Java
- Interface vs abstract class
- Method Overriding in Java
- Method Overloading in Java
- Coupling in Java
- Method to print exception information in Java
- Exception Handling by Using try-catch in Java
- Checked Exception vs Unchecked Exception
- Exception Hierarchy in Java
- Java Exception Handling Interview Questions
- final finally finalize in java
5 thoughts on “User Defined Exception in Java”