Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Creating a User Defined Exception class with Constructor having String argument in Java

Program to create a User Defined Exception class with Constructor having String argument in Java

class UserException extends Exception {

   public UserException() {
  
   }
 
   UserException(String s){
 super(s);
   }
}

public class ExceptionTest {
 
   public void method1() throws UserException{
  
    System.out.println("Throwing UserException from method1()");
 throw new UserException();
  
   }
 
   public void method2() throws UserException{
    
 System.out.println();
 System.out.println("Throwing UserException from method2()");
 throw new UserException("Exception thrown from method()2");
 
   }
    
   public static void main(String[] args) {
  
 ExceptionTest test = new ExceptionTest();

 try{
           test.method1();
 }catch(UserException e){
    e.printStackTrace(System.out);
 }
  
 try{
    test.method2();
 }catch(UserException e){
    e.printStackTrace(System.out);
 }

   }

}




Output of the program :






Video tutorial to demonstrate how to create user-defined or application specific exceptions in Java.








 
© 2021 Learn Java by Examples Template by Hubberspot