• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with user defined exception

 
Naveen Megharaj
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have created my own exception class and i m trying to throw the exception explicitly. But when i m compiling, its giving me the following error : Incompatible types error.

This is my code:


Can anybody tell me what's going wrong..??

Thanks in advance


 
Campbell Ritchie
Sheriff
Posts: 51459
87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which line is it on? And does throw new Exception().setErrorMessage("xxx") actually add up?
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm going to answer your question in two ways -- 1: to explain why your code doesn't compile, 2: to explain the proper way to write this method.

1: So as for the first part -- why your code doesn't compile:


When you use the "throw" clause, the method you call needs to return an Exception object

"throw new MyException()" in fact returns an Exception object, but you then chain that method with a call to setErrorMessage() which doesn't return anything, and so you get an incompatible Type error.

There are 2 ways you can fix this.
-- have setErrorMessage() return the MyException object.
-- construct and modify the Exception in one line, and throw the exception in the next line.

2- That being said, this isn't the "proper" way to use and define your own exception, a better way would be to define a constructor that takes the error message as an argument:


and then call the exception like this:
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15644
48
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To improve it even further:

You do not need a member variable to store the message in your own exception class, because the superclass Exception already has such a member variable. Write your own exception class by implementing four constructors, like this:

Those four constructors correspond to the constructors of the base class Exception.

And then use it like this:

Use the standard getMessage() method from class Exception to see the message:

 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
much better -- nice Jasper.
 
Naveen Megharaj
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot guys.....!!!
the information given by you was very helpful....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic