10 April 2012

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){
    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();
if (mark < 0)
throw new NegativeMarkException(mark);
System.out.println("mark entered is " + "  "+ mark);
static int getmark(){
Scanner input=new Scanner(System.in);
System.out.println("enter the mark");
int m =input.nextInt();
return m;



enter the mark
mark entered is   20

enter the mark

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


Naviya Nair said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Online Training Java EE Online Training Java EE Online Training Java 8 online training Core Java 8 online training

Java Online Training from India Java Online Training from India Core Java Training Online Core Java Training Online Java Training InstitutesJava Training Institutes

Post a Comment

Related Posts with Thumbnails

Popular Posts