Search code examples
javaexceptionthrow

Using throw for user defined exception


Following is the code where " throw use; " shows an error.Why? How to use throw for user defined exceptions?Give some example?

class use extends Exception{
public String toString() {
    return "too many exceptions";
}
}   
class user{
public static void main(String s[]) {
    int i=3;
    try {
        if(i>1)
            throw use;
    }
    catch(use e) {
        System.out.println(e.toString());
    }
    finally{
        System.out.println("program executed successfully!");
    }

}
}

Solution

  • you need an instance of the exception class to throw it:

    throw new use();
    

    or

    use a = new use();
    throw a;
    

    In the future please follow Java naming conventions, it will make your code much more readable. (class names should start with a capital letter).