I recently included a simple try catch statement in an assignment, and I wrote it as follows
try { ... }
catch (Exception NullPointerException) { ... }
Is this functionally the same as writing:
try { ... }
catch (NullPointerException e) { ... }
The code ran fine when I tested it, but I wanted to make sure I am grasping the way catch statements work correctly. Are both these formats viable?
Firstly,
The first block indicates that it is capable to handle any type of exception.
try{//code here}
catch(Exception NullPointerException){//code here}
While the second block indicates that it can handle only NullPointerException type of exception.
try{//code here}
catch(NullPointerException e){//code here}
Secondly,
There is no difference between *NullPointerException* in first block and *e* in second block. They are ultimately reference variables. It can be renamed or changed to any random name. It's behavior would be always same.
Its always
catch (ExceptionClass exceptionVariableName)
which says "catch exceptions of type ExceptionClass or its descendants and assign it to a variable exceptionVariableName
In your examples, in first case catch(Exception NullPointerException) Exception is the class and NullPointerException is non conventional variable name.
Second case catch(NullPointerException e)
NullPointerException is an exception class and e is a variable name.
Related
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 .
Is it correct to catch everything into the main? If not, why?
public static void main(String[] args) {
try {
// A lot
// of
// calls
} catch (Exception e) {
e.printStackTrace();
}
}
Generally it's better to separate out the catches IMO, so that you can handle each separately even if you end up handling these the same. It's also easier to see what the risks are, what the catch is, when you come back to your code. Just a quick example:
try {
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
request.abort();
} finally {
client.close();
}
If all you do is call e.printStacktrace (), I do not think it is worthwhile. The JVM will do something like that anyway. But I believe it is worthwhile if you output a meaningful message; stacktraces are meaningful only to programmers.
It will catch every Exception from the try{} block, It might not catch if there is another catch catching in the inner code
It depends. If you only need to show some error messages when an exception arise, I guess it's ok. But if you find the need to make some kind of processing depending on the type of exception, then you'll be better off try-catching in the inner code.
In your case it makes no sense since you do not process the exception you catch but simply print it. If you declare main throws checked_exceptions_your_code_throws_list you will get the same result (JVM will print exception) and a cleaner code. And if your code throws no checked exception then do not declare any exceptions at all.
What is the difference between these usage of try-catch blocks and when you should use each one?
try {
doSomething1();
} catch(Exception e1){
exception_handle1();
}
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
try {
doSomething1();
doSomething2();
} catch(Exception e1) {
exception_handle1();
} catch(Exception e2) {
exception_handle2();
}
try {
doSomething1();
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
} catch(Exception e1){
exception_handle1();
}
try {
doSomthing1()
catch(Exception e1){
exception_handle1()
}
try {
doSomthing2()
catch(Exception e2){
exception_handle2()
}
doSomthing1() and doSomthing2() are unrelated methods. Failure of either one of them is independent on each other.
try {
doSomthing1()
doSomthing2()
catch(Exception e1){
exception_handle1()
}catch(Exception e2){
exception_handle2()
}
We can use the try-catch block this way to stop doSomthing2() method from executing if doSomthing1() fails. We can handle each exception individually with two catch blocks. But, one important point to note is that, your 2nd catch block is an unreachable code. In general, you should have catch block for more specific exceptions first, followed by generalized exception. Now, in your case, all the exception that 2nd catch block is supposed to handle will already be handled in the first one.
try {
doSomthing1()
try {
doSomthing2()
catch(Exception e2){
exception_handle2()
}
}
catch(Exception e1){
exception_handle1()
}
We have 2 try-catch blocks embedded in each other. Even after the doSomthing2() fails the program will continue inside the try block.
Well, the obvious difference between the first and the other two is that doSomthing2 will be attempted whether or not doSomthing1 threw an exception. In the exact code you quoted, there isn't a huge difference between the second and third examples (syntax errors aside) other than that in the third example, your exception handling code for the second try is within the exception handling code for the first, and so if it throws, the throw will be caught.
Which you should use depends entirely on the situation. Sometimes, it's appropriate to run doSomthing2 whether or not doSomthing1 throws an exception. Sometimes it isn't.
If doSomThing1 fails then the code moves on to execute doSomthing2
In the second example, doSomthing2 does not get executed if doSomthing1 fails
Whereas, third example is similar to second one.
First lets asume, doSomething1() and exceltion_handle1(), don't call System.exit(x) or something.
1) So first piece of code, will doSomething1(), no matter doSomething1() will throw any Exception or not, it will handle it (process the catch code block) and advance to second try and run it the same way.
try {
doSomething1();
} catch(Exception e1){
exception_handle1();
}
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
It's morning, so I hope I won't make any wrong decisions.
2) This code will run doSomething1() then doSomething2(), and no matter which one will fail (throw Exception), only first catch clause will be called, as it absorbs all the subclasses and itself, so second catch won't be reached (first takes all the possible exceptions).
So afaik, you should get an error (shouldn't compile). It's smart and will recognize, that second catch won't be reached in any way.
The correct pattern would be : as we go to the bottom, exceptions should be broader and broader (strictly). It's logical, as order of catching clauses goes down, upper catch shouldn't be parent of bottom ones, as ANYWAY parent will take that exception, and childs in the bottom won't be reached.
Example: (I recommend you to learn about Multicatch in java.)
catch (Specific2ChildOfSpecific1 e3)
...
catch (specific1ChildOfException e2)
...
catch (Exception e1)
try {
doSomething1();
doSomething2();
} catch(Exception e1) {
exception_handle1();
} catch(Exception e2) {
exception_handle2();
}
3) This one: If doSomething1() will fail e1 catch clause will be executed and thats all, if it will pass, then if doSomething2() will run and if it fails, then e2 catch clause will be executed.
Notice # second example, no matter which doSomething will fail, e1 will be executed (don't forget there is an error as second is unreachable). But I understand what you wanted to ask.
try {
doSomething1();
try {
doSomething2();
} catch(Exception e2){
exception_handle2();
}
} catch(Exception e1){
exception_handle1();
}
its the same concept when you creating a conditionaL statement, just that conditionaL statement is testing the condition the try catch is testing an error
In try-catch syntax, does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?
Yes, Specific exception should be written first, broader after that,
Its like you call all the animals first in the room and after you try to see if there is any human outside
For example
try{
//do something
}catch(Exception ex){
}catch(NullPointerException npe){
}
Will give you compile time error
Yes. The FileNotFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
Specific Exceptions must be caught prior to general exception or else you will get an unreachable code error.
For example -
try{
//do something
}catch(NullPointerException npe){
}catch(NumberFormatException nfe){
}catch(Exception exp){
}
If you put the Exception catch block before the NullPointerException or NumberFormatException catch block, you will get a compile time error. (Unreachable code).
On a tangent, I would advise you to think twice whether you need all those catch blocks in the first place. Are you sure you are going to provide meaningful handling for each case differently? If you are just going to print out a message, you can only catch IOException to do that.
well...start from subclasses to superclass...that's the ideal way..otherwise you will get unreachable code error
Yes Of Course. The more specific exception should be written in the first catch block and the generic exceptions like catch(Exception ex){ex.printStackTrace();} should be written in the final set of catch block.
If you try the other way then, your specific exception will be unreachable by the JVM compiler!
IOException is the super class of FileNotFoundException. So, if you put the catch statement for IOException above that for FileNotFoundException, then the code for second catch will become unreachable and the compiler will throw an error for that. Reason is simple: every object of a sub class can be easily accepted by a super class reference.
IOException is the super class of FileNotFoundException .So fist catch sub class i.e FileNotFoundException and then you need to catch IOException
For Example,
try{
// something
} catch(FileNotFoundException fne){
// Handle the exception here
} catch(IOException ioe) {
// Handle the IOException here
}
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?
}