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

1 comment :

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


Copyright © Rough Record. Designed by OddThemes