Creating your own custom Exception Class in Java

Here is a small and easy example which reflects the use of customized exception classes. The use of this concept can be done in case you want to create your own customed exception class. This concept can be used if you want to display or trigger your own exception message own certain conditions or situations in your coding or program.

Here are two classes “MyException” and “MyEx”, both are customed exception classes you can use any type among the two to create your own customed exception class.

class MyException extends Exception{
    public String toString(){
        return "It\'s My Exception";
    }
}

class MyEx extends Exception{
    MyEx(String s){
        super(s);
    }
}

class J{
public static void main(String[] args){
System.out.println("Hello");
        try{
            int n=Integer.parseInt(args[0]);
            if(n>10){
                //throw new MyException();
                throw new MyEx("It\'s Exception");
            }
        }catch(Exception e){
        System.out.println("exception:"+e);
        }finally{
        
        System.out.println("finally");
        }
        
}
}

Save this file with your own choice of name, compile it and run it using command : java J
enable/disable the two statements inside if block to see the effect of both the customed exception classes.

Here is another example in which our exception class has extened the superclass Throwable.

class MyException extends Throwable{
public String toString(){
return “It\’s My Exception”;
}
}

class I{
public static void main(String[] args){
System.out.println(“Hello”);
try{
int n=Integer.parseInt(args[0]);
if(n>10){
throw new MyException();
}
}
catch(Throwable e){
System.out.println(e);
}
finally{
System.out.println(“In finally”);
}
}
}