Share on Google+Share on Google+

Java User-defined Exception

Advertisement
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.

Advertisements

Posted on: November 28, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.