PCP PCP - 8 days ago 5
Java Question

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 print
e.getMessage()
,
I get nothing(blank).

How I can make custom
e.getMessage()
?

Thanks..!

PVR PVR
Answer

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;
     }
 }
Comments