Java User-defined Exception


 

Java User-defined Exception

In this tutorial, you will learn about the User-defined Exceptions.

In this tutorial, you will learn about the User-defined Exceptions.

Java User-defined Exception

In this tutorial, you will learn about the User-defined Exceptions. These custom exceptions actually all the programmer to handle errors in the applications with customized responses. It creates the java application more user friendly and easily understood. The given example throw a user defined exception if the student marks entered, is less than fifteen.

Example:

import java.util.*;
class MyException extends Exception{
String str;
MyException(String st) {
str=st;
}
public String toString(){
return ("Invalid Marks entered! "+ str) ;
}
}

class UserDefinedException{
public static void main(String args[]){
try{
Scanner input=new Scanner(System.in);
System.out.print("Enter marks: ");
int marks=input.nextInt();
if(marks < 15){
throw new MyException("Error! Marks are less than 15.");
}
}
catch(MyException e){
System.out.println(e) ;
}
}
}
Output
Enter marks: 10
Invalid Marks entered! Error! Marks are less than 15.

Ads