Home Tutorial Java Core Java User-defined Exception

 
 

Java User-defined Exception
Posted on: November 28, 2012 at 12:00 AM
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.

Related Tags for Java User-defined Exception:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.