I'm reading exception handling in the book "A programmer guide to Java SCJP certificate". The author wrote that :
If a checked exception is thrown in a method, it must be handled in one of three ways:
1.By using a try block and catching the exception in a handler and dealing with it
2.By using a try block and catching the exception in a handler, but throwing
another exception that is either unchecked or declared in its throws clause
3.By explicitly allowing propagation of the exception to its caller by declaring it
in the throws clause of its method header
I understood clearly the first and third, but the second made me a lot of confused. My concerns are that :
-It's still alright even if I don't throw any other unchecked exceptions, so why do we have to throw another exception at here?
-Why do we have to re-declare the exception that we have caught, in throws clause? I think it's over by the handler.
Thanks to everyone.
The book just list three allowed options.
-It's still alright even if I don't throw any other unchecked exceptions,
so why do we have to throw another
exception at here?
You might want to throw another more descriptive exception, for example adding more info.
-Why do we have to re-declare the exception that we have caught, in
throws clause? I think it's over by
the handler.
You don't have to re-declare. But if the new exception you are throwing is checked, then you must declare it in the throws clause. In fact the exception you just caught doesn't need to be declared even if checked.
You may want to do this to catch a checked exception and throw another checked exception of a different kind. Perhaps you want to throw your own exception rather than a different one.
public void doSomething() throws MyCheckedException {
try {
doSomethingThatThrowsSpecificCheckedException();
} catch(SpecificCheckedException e) {
throw new MyCheckedException();
}
}
Or you can throw an unchecked exception (something that is or extends RuntimeException).
public void doSomething() {
try {
doSomethingThatThrowsSpecificCheckedException();
} catch(SpecificCheckedException e) {
throw new RuntimeException();
}
}
First of all, you should declare in the throw clause the exception that you throw, not the one you caught, assuming you are throwing a checked exception.
Second, you don't have to do that. It is just one of the three options.
Why would you do that? Usually this is done between the application layers. For example, Hibernate catches SQLExceptions and rethrows them as unchecked HibernateException, so that code that calls Hibernate methods doesn't have to be polluted with the try/catches for SQLExceptions. Another option is to translate a low-level exception into some business logic exception that can be handled up the stack. This allows for the better isolation of the business logic from the low level implementation details.
Great question, and one which good java programmers should get their head around.
It's all about adhering to the method signature that defines the method's contract with its caller, and which includes what exceptions you are going to throw.
Option 1 is dealing with the exception
Option 2 is not dealing with the exception, but keeping the same contract
Option 3 is not dealing with the exception and changing your contract
A implementation of the pattern in option 2 would be:
public interface Server {
public void useServer() throws ServerException;
}
public class ExplodingClient {
private Server server = new ServerImpl();
public void doIt() throws ClientException {
try {
server.useServer();
} catch (ServerException e) {
// Our contract doesn't allow throwing ServerException,
// so wrap it in an exception we are allowed by contract to throw
throw new ClientException(e);
}
}
}
public class SilentClient {
private Server server = new ServerImpl();
public void doIt() {
try {
server.useServer();
} catch (ServerException e) {
// Our contract doesn't allow throwing any Exceptions,
// so wrap it in a RuntimeException
throw new RuntimeException(e);
}
}
}
By using a try block and catching the
exception in a handler, but throwing
another exception that is either
unchecked or declared in its throws
clause.
Handling the exception in Java can be done in two ways :
Wrapping it in try-catch-finally block.
Declaring the method to throw ( using throws) the exception to the caller of method to handle.
-It's still alright even if I don't throw any other unchecked exceptions,
so why do we have to throw another
exception at here?
Throwing another exception means describing more about it. Also, to let the caller of the method know that this particular exception was generated.
-Why do we have to re-declare the exception that we have caught, in
throws clause? I think it's over by
the handler.
Redeclaring exception that you just caught in the catch block is to make the caller of this method alert that this method could throw a particluar exception. So be prepare to handle it.
You must go over this Jon Skeet's post : Sheer Evil: Rethrowing exceptions in Java
Remember, you are never forced to handle the unchecked exceptions, compiler forces you to just catch the checked one.
Related
So im reading the below and i understand why you would do it..
https://jenkov.com/tutorials/java-exception-handling/exception-wrapping.html
example :
try{
dao.readPerson();
} catch (SQLException sqlException) {
throw new MyException("error text", sqlException);
}
So what if i want to isolate all external exceptions inside the dao layer only, and only use my exceptions. so in the above example i dont want to send SQLEXception inside the constructor, would doing the below be enough. Would it contain enough information :
throw new MyException("error text", sqlException);
or maybe my constructor should be the following instead
public MyException(String text,Exception ex)
You can inherit your exception from Exception like
MyException extends Exception {
}
and then use try catch like :
try {
dao.readPerson();
} catch (MyException ex) {
// handle Exception
}
by doing this you can do whatever you want in your class and i think its cleaner than other ways.
It will trigger automatically so you dont need to raise an exception.
If you want to catch SQL Exceptions only you can inherit MyException from SqlException so it will only trigger when SqlException happens
I understand that you worry about the catching part of your code knowing about the wrapped exception. In "not knowing" there are different layers.
Level 1: Nothing obligates the catching class to get the cause and therefor explicitly knowing about the SQLException. They just catch the MyException and don't care what's wrapped in it. Usually that's enough.
Level 2. Another level of not knowing is restricting the catching class to even have access to the wrapped exception. In that case why wrap it at all? Just catch the SQLException in your DAO layer and throw MyException without wrapping the original exception in it.
About wrapping the causing Exception instead of the original one. You could do that but you might lose valuable information so 99% of the time it's not recommended. There are some corner cases where I've done it though. Let's say you throwing code runs asynchronously through ExecutorService. Then if an exception is thrown it's wrapped to ExecutionException, but as a caller I might not be interested that the code ran asynchronously so I catch the ExecutionException, get it's cause (the actual exception that happened) and wrap that to my custom exception.
Consider following example. Is it considered a bad practise?
Note: I know re-throwing exception is ok, but what about assertionerror?
public static main(){
try {
doSmth();
} catch (WhateverException we) {
throw new AssertionError(e.getMessage());
}
}
public static void doSmth() throws WhateverException { }
It's not bad practice to throw an error in response to an exception, if the exception indicates a situation that is fatal for your code. However:
There's no need to use AssertionError in particular. I mean, it's fine if you do, since nobody's going to be catching one, but you should consider just doing Error instead, so that somebody doesn't go looking for the assert statement that they assumed caused it.
When chaining a throwable like that, always use the old exception to construct the new one: throw new AssertionError(we). That'll keep the old stack trace around. You can (and should) also pass a custom message.
I have a bit of confusion in the following snippet.
try {
public static void showMyName(String str) throws IOException
{
if(str.equals("What is your Name?"))
throw new IOException;
}
}catch(IOException e)
{
System.out.println ("Exception occurs , catch block called")
}
Now, my question is what is difference between throws IOException && throw new IOException
Why don't we require to use catch , finally block for throws IOException ?
How does throws is handle the exception. ?
When an Exception is generated, there are two ways to deal with it.
Handle the Exception - this uses catch block
Declare the Exception - this uses throws block
So, dealing with an already generated exception is done by catch or throws.
On the other hand, throw is used while an Exception is "generated".
Typically, the throw keyword is used when you're instantiating an Exception object or while cascading an already generated exception to the caller.
For example,
public void doSomething(String name) throws SomeException { // Exception declared
if( name == null ){ // cause of the exception
throw new SomeException(); // actual NEW exception object instantiated and thrown
}
// Do something here
.
.
.
}
In the calling method,
public static void main(String[] args) throws SomeException{ // Need to declare exception because you're "throwing" it from inside this method.
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
throw e;// throw the exception object generated in doSomething()
}
}
Alternately, you can "handle" the exception in the catch block:
public static void main(String[] args) { // No need to declare exception
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
System.out.println("Exception occurred " + e.getMessage()); // Handle the exception by notifying the user.
}
}
Hope this helps.
Addendum - Exception Handling glossary
try - used for invoking code that can potentially cause exceptions or with resources such as Files/Streams/Network/Database connections.
catch - used immediately after a try block to "handle" or "throw" exceptions. Optional if finally is used.
finally - used immediately after a try or catch block. Optional. Used for executing code that "must" be executed. Code within a finally block always gets executed - even if the try or catch has a return statement.
throw - used to "push" or "cascade" exceptions through the calling methods. Always used inside a method.
throws - used to "declare" that a method will be throwing an exception if something goes wrong. Always used as part of method signature.
Addional Reading
Here's an elaborate article to help you understand the try-catch-finally semantics in java.
Update
To answer your other question,
Why don't we require to use catch , finally block for throws
IOException ?
Think of catch and throws as mutually exclusive constructs. (This is not always true, but for your understanding, it's good to start with this thought.)
You declare a method that it throws IOException. This piece of code is written at a point where you declare the method. And, syntactically, you cannot place a method declaration inside a try block.
How does throws is handle the exception. ?
Like I mentioned before, catch and finally are used during exception handling. throws is just used to cascade the exception back to the caller.
throw new IOException means that you encountered some error condition and decided to break the flow of the program by throwing an exception.
If that exception is a checked exception (i.e. not Error or RuntimeException), you must either catch that exception in a catch block, or declare in the method's signature that the method is expected to throw that exception (or a super-class of that exception). That's what the throws IOException means.
You are pretty much right on. Except for one thing I'll mention in a bit.
throws is as much a part of the method API as the name and the parameters. Clients know if they call that method, they need to handle that exception--by simply throwing it also or by catching it and handling it (which may in fact entail the throwing of another exception wrapping the original). throws is addressed at compile time.
throw is the actual act of letting the runtime know something bad happened--that the exceptional condition we were worried about has in fact taken place. So it needs to be dealt with at runtime.
But you weren't quite right when you said, "Throws in method signature should always appear if there exist a throw statement in the method." That is often true but not always. I could also call another method that throws an exception within my method, and if I don't catch it, my method needs to throw it. In that case, there is no explicit throw of the same exception by me.
The final point is that you only need to declare an exception in throws when the exception is a checked exception--meaning it is from the other side of the Exception class hierarchy from RuntimeException. Common checked exceptions are IOException and SQLException. Checked exceptions must be listed in the throws part of the method signature if you don't handle them yourself. Anything subclassing RuntimeException--like NoSuchElementException in your example and also the hated NullPointerException--is an unchecked exception and doesn't have to be caught or thrown or anything.
Typically, you use checked exceptions for recoverable problems (where the client knows what can happen and can gracefully handle the problem and move on) and unchecked exceptions for catastrophic problems (like can't connect to the database).
If you can get past all the AOP stuff, this is a great discussion of how you use checked and unchecked exceptions effectively.
The first biggest difference is throw can throw exception like you throw stone in river,
and throws state that this method have chances to throw exception but may not also... and thats why throws dont need try catch because it state already that it gona throw some kind of exception.
throws keyword means that this method will throw any Exception that will have to be handled in a higher level.
public static void showMyName(String str) throws IOException
If another method call this method, it has to catch this exception or throw it one more time (by typing throws in its signature).
Catch the exception or keep throwing it, depends on your business logic.
Assume that we got an remote ejb which provides a asynchronous method with exception
#Stateless
public class MyBean {
...
#Asynchronous
public Future<Void> doSomething()
throws MyException
{
//implementation
}
...
}
Now the client side:
try {
Future<Void> result = myBean.doSomething()
}
catch(MyException e)
{
//Useless required catch block?
}
I know that the exception can be retrieved of the Future object when it is returned.
My question is if there is a better implementation without that useless empty catch block which will not be called anyway.
Another solution will be to make MyException to extend RunTimeException like this. Not sure if this is possible for you. Notice the annotaiton with rollback=false (Assuming you have a checked exception without rollback set to true). This way you don't have to mention it in the throws clause or catch it. The annotation will make sure that it will not be wrapped in EJBException.
#ApplicationException(rollback = false)
public class MyExcepton extends RuntimeException {
...
}
Indeed, if you throw your custom exception, then you decided that the calling code has to deal with it and you do so by catching it as with any synchronous method. And if you are saying, the catch block is useless, then the question is, why you throw the exception at all?
To avoid dealing with the exception in the client code, you may instead return an object holding the outcome of the call, which can then be an error that occurred. You still need to handle this situation, but you won't need a try-catch-block. See this post for an example.
Further reading: Java EE Tutorial.
So I have a pretty big java application that I wrote a year ago and I'm trying to understand it again. I'm looking at a method in the code where there is an obvious risk of getting NoSuchElementException: I'm calling .next() on a scanner variable that has been constructed with an arbitrary string. The only thing the method is declared to throw are custom made subclasses of Exception. The risky command isn't written in a catch-block either. The code compiles and works fine and when I use my gui in such a fashion that it should throw a NoSuchElementException nothing happens :O
As a test I wrote a catch-block into the code, compiled it, ran the gui and made it throw NoSuchElementException again and the application successfully caught the exception and acted accordingly. How is it that I can compile the code without specifying the this exception may be thrown? If it's any use at all, here is the code without the catch-block:
public static Expression interpret(final Scanner scanner)
throws
InvalidPosition,
NoSuchSpreadsheet,
IllegalStartOfExpression,
InvalidExpression,
FalseSyntax,
InvalidRange {
String keyword = null;
try {
keyword = scanner.next();
} catch (NoSuchElementException e) {
throw new IllegalStartOfExpression();
}
switch(keyword) {
case "Get":
Position pos = PositionInterpreter.interpret(scanner.next());
Expression expression = Application.instance.get(pos);
if (expression instanceof Text) {
System.out.println("Failure");
} else { System.out.println("Success"); }
return new Text(expression.toString());
case "Int":
return new Int(
scanner.nextInt());
As you can see, the method simply assumes that there is more than one word in the scanner after checking if there is at least the one. How am I getting away with compiling this?
It is be cause NoSuchElementException is unchecked exception, which means that it "is-a" RuntimeException which does not force you to catch.
The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers. See ref for a description of the exception class hierarchy and some of the exception classes defined by the Java API and Java virtual machine.
Runtime exceptions serve the same purpose as checked exceptions; to communicate exceptional conditions (unexpected failures, etc) to the user.
checked exception forces the caller of a method to handle that exception, even if they do not know how to handle it. Often times, developers will end up catching the checked exception, only to re-throw it (or another exception). Hence the Runtime exceptions
Here is the exception hierarchy
As the question has already been answered, I'd like to point on that this is very poor design and not the intended usage of the Scanner class:
try {
keyword = scanner.next();
} catch (NoSuchElementException e) {
throw new IllegalStartOfExpression();
}
What you should really be doing is ask the scanner whether there is any input, and only then retrieving it, like so:
if(scanner.hasNext()) {
keyword = scanner.next();
}
else {
throw new IllegalStartOfExpression();
}
The same applies to the line which is causing your problem:
if(scanner.hasNextInt()) {
return new Integer(scanner.nextInt());
}
java.util.NoSuchElementException is a subclass of java.lang.RuntimeException. RuntimeExceptions don't have to be handled. From the Java API documentation:
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.