my dog learned polymorphism*
The moose likes Beginning Java and the fly likes How to throw Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to throw Exceptions" Watch "How to throw Exceptions" New topic
Author

How to throw Exceptions

Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176




Hello everyone,

I have a project to do and my professor wants us to create our own methods that can throw an exception. Not having any idea how to do this I check Java's official site:
http://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.html
I looked at the first example on that page and this something similar to parseExpression(String) without putting throws ParseException. But the complier gave me an error "unreported Exception".
I reread the criteria that we were given and realized that our professor gave us the method signature for parseExpression(String) and that it included "throws ParseException" at the end. So I added that as you can see in the code and it got rid of the syntax errors.

However when I call the method without putting it inside a try{} it compiles are runs, which it isn't meant to, the compiler should normally tell me "expection must be caught or throw". And thus this method doesn't throw a ParseException when there is an error in String expr's format.

Help please I've only got until the end of this week to complete this.

Thanks in advance.


Olly
Sunil Kumar
Ranch Hand

Joined: Apr 24, 2007
Posts: 76
It should give an error unless you are again using throws in the method where you are calling parseExpression method.
FYI, All exceptions that extends RuntimeException doesn't require any try/catch block.


Sunil Kumar
http://goodtoknowit.blogspot.com/
Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

No it doesn't give an error, that's the problem. Here is the class I used to test:


The first one gives me -2.0 as in should. And the second one gives me -2.5, when it should be giving me an error.
Olivier Legat
Ranch Hand

Joined: Nov 17, 2007
Posts: 176

Ok I found my error, it was a problem with my testing code. In the second test I wrote simpleParseExpression instead of parseExpression.

All is good Thanks for your help Sunil
 
wood burning stoves
 
subject: How to throw Exceptions