Prakash P
Prakash P

Reputation: 4058

Java custom exception

I have successfully implemented a custom exception using below code

CarNotFoundException.Java

 public class CarNotFoundException extends Exception 
       {        
            private static final long serialVersionUID = 1L;

            public CarNotFoundException(String msg) {
                super(msg);
            }
        }

Car.Java

public static CarProvider getInstanceByProvider(String provider) throws CarNotFoundException {
        if(!provider.equals(Constants.BMW || Constants.B||Constants.C{ 
            throw new CarNotFoundException("Car Not Found");
            }   
        return carProvider;
    }

CarTest.java

        try 
        {
          carProvider = Car.getInstanceByProvider(provider);    
        } catch (CarNotFoundException e) {
            e.printstacktrace();
        }

What I want to do ?

Instead of e.printStackTrace(); when I calle.getMessage(), I get nothing(blank).

How I can make custom e.getMessage() ?

Edit : I got my answer, I missed System.out.println()

Thanks for helping..!

Upvotes: 2

Views: 240

Answers (1)

PVR
PVR

Reputation: 915

Override getMessage() method in your custom exception

public class CarNotFoundException extends Exception 
{        
     private static final long serialVersionUID = 1L;

     public String message;

     public CarNotFoundException(String msg) {
         this.message = msg;
     }

  // Overrides Exception's getMessage()
     @Override
     public String getMessage(){
         return message;
     }
 }

Upvotes: 1

Related Questions