Powered by Blogger.

Program for User defined Exception in java

>> Monday, April 18, 2011

To create user defined exception first you should create a class by extending Exception class.

class BadString extends RuntimeException{

}

Create  another class  named as "UserExcep" to throw our own exception.

public class UserExcep


Write some logical conditions to throw your exception and the exception caught by catch block.

package javabynataraj.exceptions;

import java.io.BufferedReader;
import java.io.InputStreamReader;

class BadString extends RuntimeException{

}
public class UserExcep{
    public static void main(String[] args) {
        try{
            System.out.println("Enter the String: ");
            BufferedReader sb=new BufferedReader(new InputStreamReader(System.in));
            String s=sb.readLine();
            if(s.equals("hateyou")){
                throw new BadString();
            }
            System.out.println("I Accept your String");
        }catch(Exception e){
            System.out.println("Please enter a good String");
            //e.printStackTrace();
        }
    }
}


Introduction to Java Programming, Comprehensive (8th Edition)

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.