2

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..!

6
  • 1
    whats this ProviderNotFoundException ? is it custom? Commented Nov 26, 2016 at 9:03
  • 1
    Your custom exception seems to be CarNotFoundException, but you're catching a ProviderNotFoundException. The e.getMessage() will work just fine with the code in CarNotFoundException. Commented Nov 26, 2016 at 9:03
  • wish you said it sooner. i have already post an answer Commented Nov 26, 2016 at 9:13
  • Are you sure you are calling e.getMessage() ? There is no problem with the code you are showing above. Commented Nov 26, 2016 at 9:31
  • 1
    e.getMessage() will get the message. Are you printing it? System.out.println(e.getMessage()); Commented Nov 26, 2016 at 9:36

1 Answer 1

1

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;
     }
 }
Sign up to request clarification or add additional context in comments.

9 Comments

tried this but not working public class CarNotFoundException extends Exception { private static final long serialVersionUID = 1L; private String message; public CarNotFoundException(String message) { this.message = message; } @Override public String getMessage() { return message; } }
What message you get?
I get nothing, blank message
Write System.out.print(e.getMessage());
This is totally unnecessary, as similar code already exists in Throwable.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.