Tuesday, April 16, 2013

User Defined Exception in Java with Example



User defined Exception in Java


Hello Friends,


 

                        In this article we will see User Defined Exception. User Defined Exception means exception class created by User. Built-in exceptions provided by the Exception and Error classes may not always be enough to trap errors occurring in the program. There may be case where there is a need to create user-defined exceptions. User-defined class should be subclass of the Exception class.

The advantage of sub-classing the exception the Exception class is that the new exception type can be caught separately from other subclasses of Throwable.

Example of User-defined Exception is following,


class UseDefinedException extends Exception{
                String msg = "";
                int marks;
                public UseDefinedException(){

                }
                public UseDefinedException(String str){
                                super(str);
                }
                public String toString(){
                                if(marks <= 50){
                                                msg = "You have failed";
                                }

                                if (marks > 50){
                                                msg = "You have Passed";
                                }
                                return msg;
                }
}

public class Test{
                public static void main(String args[]){
                                Test t = new Test();
                                t.method();
                }
                public void method(){
                                try{
                                                int i=0;

                                                if( i < 50)
                                                                throw new UseDefinedException();

                                }
                                catch(UseDefinedException ude){
                                                System.out.println("User Defined Exception :: "+ude);
                                }
                }
}

It's Output will be,
 



1 comment:

  1. thank you for sharing nice article in your blog
    visit
    web tutorial programming
    https://www.welookups.com

    ReplyDelete