I have several custom Exception classes. (Diffrent Error Codes / Error Messages)
Some of those lead to termination. This is why i let them propagate to the main.
To print the error code + message.
If I catch the superclass, is there a way without having a long if else list to check which subclass i have cought to get to the overriden method?
Would it be more readable to have several catch statements?
Should I cast them at a lower level to a higher Exception and only catch this exception?
If you need to handle a SubclassOfException in a particular way, use catch SubclassOfException.
There's no point in using a chain of instanceof checks when this is basically what the exception handling already does.
try {
} catch (SubclassOfException e) {
// Do something specific to SubclassOfException
} catch (Exception e) {
// Do something for other types.
}
is basically the same as:
try {
} catch (Exception e) {
if (e instanceof SubclassOfException) {
// Do something specific to SubclassOfException.
// Note that you have to cast explicitly if you want to use
// subclass-specific properties of SubclassOfException.
} else {
// Do something for other types.
}
}
I think it is clear that the first is more readable, and it will be more efficiently executed, since this is how the JVM expects exception handling code to be written.
Another advantage of writing in the first way is that you can't write:
try {
// ...
} catch (SubclassOfException e) {
} catch (SubclassOfSubclassOfException e) {
}
because the first catch would catch all exceptions to be matched by the second catch, making the second catch redundant. As such, this is a compile-time error, described in JLS Sec 11.2.3:
It is a compile-time error if a catch clause can catch an exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.
You need to catch the most-specific types first, and the least-specific types after.
On the other hand,
if (e instanceof SubclassOfException) {
} else if (e instanceof SubclassOfSubclassOfException) {
}
isn't a compile-time error, even though the second branch cannot be executed either; you'd just see all SubclassOfSubclassOfExceptions being handled as if they were mere SubclassOfExceptions.
Related
I'm going through our code for our core programs to refactor and I encountered this weird try/catch block
try {
//Do some socket and network stuff
} catch (NoRouteToHostException e) {
throw e;
} catch (UnknownHostException e) {
throw e;
} catch (IOException e) {
throw e;
} finally {
//Does some counting stuff over here
}
Now I can't understand why on earth someone would do something like this, the people who wrote this code have left the company, but were indeed very skilled.
Is there a purpose to this try/catch block? Would it not be better to just throw these exceptions and do the finally things from where the method is called?
If you do literally nothing with the exception before you rethrow it, there is no point in catching it. Remove the catch block for that particular exception.
try doesn't need any catch blocks, provided there is a finally.
Note that catch (SomeException e) {} is doing something with the exception: it is swallowing it (which is likely not advisable anyway). As such, you cannot remove this without changing semantics.
The only exception (no pun intended) is if you don't want to catch a particular subclass of an otherwise-caught exception. For example:
try {
} catch (FileNotFoundException e) {
throw e;
} catch (IOException e) {
// Do something.
}
If you were to remove the catch/rethrow of FileNotFoundException, it would change the semantics because it would be handled by the more-general IOException. As written, a FNFE will "leap frog" the catch block for IOE.
(This is only very occasionally useful).
Either they didn't know they could write try-finally without catch or it's a legacy piece and it formerly performed something different for each catch block.
Otherwise, it makes no sense and it's identical to
try {
// Do some socket and network stuff
} finally {
// Does some counting stuff over here
}
Even skilled people tend to make mistakes, particularly when a deadline approaches.
If you throw every exception you catch, you will end up with an unhandled exception and your application will crash. At some point in your code, you will have to decide how you will deal with the error. If you are writing a GUI application this may be at the GUI layer, where you display an error message to your user. However, throwing all exceptions caught is no different to simply marking your method with throws IOException, ....
Also, since Java 7, you can use try-with-resources, for example:
try (Socket socket = serverSocket.accept()) {
socket.getInputStream() // whatever
} catch (IOException e) {
doSomething(e);
}
Note that you can still omit the catch block and simply pass the exception up to the enclosing scope.
Today I wrote some Java which was structured something like this:
if (someCondition) {
try {
doSomething();
} catch (SomeException e) {
handleException(e);
}
}
It looked somewhat ugly so I decided to remove excesss {}-block from it.
if (someCondition) try {
doSomething();
} catch (SomeException e) {
handleException(e);
}
Which made me think that the try keyword is actually redundant. Isn't catch or finally after {}-block enough to inform the compiler / programmer that exceptions thrown inside the block have special handling?
EDIT: To clarify I don't mean that the whole try block is redundant. Just that the try keyword is. Above example would be written as:
if (someCondition) {
doSomething();
} catch (SomeException e) {
handleException(e);
}
EDIT: As requested here is a example method without if:
public void someMethod() {
{
doSomething();
} catch (SomeException ex) {
handleException(e);
}
}
Again, clear without the try keyword.
As per Java Syntax : catch block should be associated with try block as per java syntax.
IF you do not write try and write only catch block then java compiler throws error.
Why is it designed so : why we need to associate every catch/finally block with try is to write exception specific code that should be executed in case of exception in the associated try block.
If java is designed to proceed without try block then programmer does not know what specific code to be written catch block and ends up writing fallback code for all kinds of exceptions in one catch block resulting in execution of all catch block code for any kind of exception.
Also as per your doubt that placement of catch block, if you don't write try then catch block (if designed so by Java designers) has to handle exception generated in the entire code written above it which leads to the scenario explained in the above paragraph.
So, it is better to have code which may generate exception and associate with catch block which can have specific code to handle that exception.It is also the same purpose of writing multiple catch blocks after try block, with most specific or possible exception in first catch block and having the generic catch exception block at the last.
The Try block lets the catch block now what is going on inside of him .
How can I make an if statement to check if "NoSuchElementException" is returned from a function? Something similar to what I have below.
if (functionReturns == "NoSuchElementException")
How can I make an if statement to check if NoSuchElementException" is
returned from a function?
If you meant that your function returns a String with the value as NoSuchElementException, use equals instead of == :
if("NoSuchElementException".equals(functionReturns)) { }
If you meant that your function can throw a NoSuchElementException, use a try-catch. The catch block will be triggered when the function throws a NoSuchElementException.
try {
function();
} catch(NoSuchElementException e) {
//NoSuchElementException was thrown
}
If you meant that your function actually returns an instance of NoSuchElementException, you can use :
NoSuchElementException.class.isAssignableFrom(functionReturns)
If method is throwing exception then simple use try and catch .
like
boolean isException = false;
try{
//method that throws
}catch(NoSuchElementException e){
isException = true;
//or perform what you like
}
First of all NoSuchElementException or any other Exception is basically Thrown by a method not Returned. So you can/should not check it via return type.
The best approach to handle any type of Exception is try catch blocks. Ex:-
try {
// Probable Exception Throwing code
} catch(NoSuchElementException e) {
// handle/log specific type of error
}
catch(Exception e) {
// handle/log Generic error if none specific is defined
}
Find more about Exception in the Official Docs here
if you are using if statement then there must be thrown more than one error so in java 7
In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch.
Before Java 7 you would write something like this:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(NoSuchElementException e) {//work as if if (functionReturns == "NoSuchElementException")
logger.log(e);
} catch(NoSuchElementException1 e) {//work as if if (functionReturns == "NoSuchElementException1")
logger.log(e);
} catch(NoSuchElementException2 e) {//work as if if (functionReturns == "NoSuchElementException2")
logger.severe(e);
}
As you can see, the two exceptions NoSuchElementException1 and NoSuchElementException2 are handled in the same way, but you still have to write two individual catch blocks for them.
In Java 7 you can catch multiple exceptions using the multi catch syntax:
try {
// execute code that may throw 1 of the 3 exceptions below.
//combind way to catch multiple error
} catch(NoSuchElementException1 | NoSuchElementException2 e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
Notice how the two exception class names in the first catch block are separated by the pipe character |. The pipe character between exception class names is how you declare multiple exceptions to be caught by the same catch clause.
This way worked for me.
if(function.equals("NoSuchElementException"))
In Java, is there any way to get(catch) all exceptions instead of catch the exception individually?
If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).
The code looks like:
public void someMethode() throws SomeCheckedException {
// code
}
Then later you can deal with the exceptions if you don't wanna deal with them in that method.
To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)
try {
// exceptional block of code ...
// ...
} catch (Exception e){
// Deal with e as you please.
//e may be any type of exception at all.
}
The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').
If you want to handle your own exceptions first simply add a catch block before the generic Exception one.
try{
}catch(MyOwnException me){
}catch(Exception e){
}
While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.
try{
// IO code
} catch (Exception e){
if(e instanceof IOException){
// handle this exception type
} else if (e instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
throw e;
}
}
However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable
try{
// IO code
} catch (Throwable t){
if(t instanceof Exception){
if(t instanceof IOException){
// handle this exception type
} else if (t instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else if (t instanceof Error){
if(t instanceof IOError){
// handle this Error
} else if (t instanceof AnotherError){
//handle different Error
} else {
// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else {
// This should never be reached, unless you have subclassed Throwable for your own purposes.
throw t;
}
}
Catch the base exception 'Exception'
try {
//some code
} catch (Exception e) {
//catches exception and all subclasses
}
You may catch multiple exceptions in single catch block.
try{
// somecode throwing multiple exceptions;
} catch (Exception1 | Exception2 | Exception3 exception){
// handle exception.
}
It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.
For most file operations, IOException is the root exception. Better to catch that, instead.
Do you mean catch an Exception of any type that is thrown, as opposed to just specific Exceptions?
If so:
try {
//...file IO...
} catch(Exception e) {
//...do stuff with e, such as check its type or log it...
}
Yes there is.
try
{
//Read/write file
}catch(Exception ex)
{
//catches all exceptions extended from Exception (which is everything)
}
This may seem like a programming 101 question and I had thought I knew the answer but now find myself needing to double check. In this piece of code below, will the exception thrown in the first catch block then be caught by the general Exception catch block below?
try {
// Do something
} catch(IOException e) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}
I always thought the answer would be no, but now I have some odd behaviour that could be caused by this. The answer is probably the same for most languages but I'm working in Java.
No, since the new throw is not in the try block directly.
No. It's very easy to check.
public class Catch {
public static void main(String[] args) {
try {
throw new java.io.IOException();
} catch (java.io.IOException exc) {
System.err.println("In catch IOException: "+exc.getClass());
throw new RuntimeException();
} catch (Exception exc) {
System.err.println("In catch Exception: "+exc.getClass());
} finally {
System.err.println("In finally");
}
}
}
Should print:
In catch IOException: class java.io.IOException
In finally
Exception in thread "main" java.lang.RuntimeException
at Catch.main(Catch.java:8)
Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).
Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.
Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).
The Java Language Specification says in section 14.19.1:
If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
Reference:
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134
In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.
One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.
If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:
public void doStuff() throws MyException {
try {
//Stuff
} catch(StuffException e) {
throw new MyException();
}
}
And now your compiler will not yell at you :)
No -- As Chris Jester-Young said, it will be thrown up to the next try-catch in the hierarchy.
As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).
It won't be caught by the second catch block. Each Exception is caught only when inside a try block. You can nest tries though (not that it's a good idea generally):
try {
doSomething();
} catch (IOException) {
try {
doSomething();
} catch (IOException e) {
throw new ApplicationException("Failed twice at doSomething" +
e.toString());
}
} catch (Exception e) {
}
No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one)
Old post but "e" variable must be unique:
try {
// Do something
} catch(IOException ioE) {
throw new ApplicationException("Problem connecting to server");
} catch(Exception e) {
// Will the ApplicationException be caught here?
}