Java Exercise 3 : user defined exception class.




While defining an user defined exception, we need to take care of the following aspects:
  • The user defined exception class should extend from Exception class.
  • The toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class NegativeMarkException extends Exception {
private int Mark;
public NegativeMarkException(int mark){
this.Mark=mark;
}
    public String toString(){
    return "mark cannot be negative";
    }
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



import java.util.*;
public class UserDefinedException{
public static void main(String[] arg) throws Exception{
int mark = getmark();
try{
if (mark < 0)
throw new NegativeMarkException(mark);
else
System.out.println("mark entered is " + "  "+ mark);
}
finally
{
}
}
static int getmark(){
Scanner input=new Scanner(System.in);
System.out.println("enter the mark");
int m =input.nextInt();
return m;
}

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




Output

enter the mark
 20
mark entered is   20




enter the mark

-20
Exception in thread "main" mark cannot be negative
at UserDefinedException.main(UserDefinedException.java:7)















Post a Comment

Copyright © Rough Record. Designed by OddThemes