File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes problem with user defined exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "problem with user defined exception" Watch "problem with user defined exception" New topic

problem with user defined exception

Naveen Megharaj
Ranch Hand

Joined: Feb 13, 2009
Posts: 39
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

Joined: Oct 13, 2005
Posts: 46405
Which line is it on? And does throw new Exception().setErrorMessage("xxx") actually add up?
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

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:

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15093

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:

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

much better -- nice Jasper.
Naveen Megharaj
Ranch Hand

Joined: Feb 13, 2009
Posts: 39
thanks a lot guys.....!!!
the information given by you was very helpful....
I agree. Here's the link:
subject: problem with user defined exception
jQuery in Action, 3rd edition