This question already has answers here:
Question about multiple 'catch'
(9 answers)
Closed 7 years ago.
When we use try-catch blocks, can we use multiple catch blocks with one try block?Is it a must to have catch block when a try block present?
Since different types of exceptions can be thrown from a single try block, multiple catch blocks can obviously be used with one try block to catch those exceptions.
It is a must to use catch block or finally block. If there's neither of them then it will be a compilation error. Therefore if there's a try block present and there's no finally block then it is a must to use catch block.
There are two possible ways (for example):
try {
// some code to access to a db
} catch (IOException ex) {
logger.log(ex);
throw ex;
} catch (SQLException ex) {
logger.log(ex);
throw ex;
}
Since Java 7 it is possible to use this way:
try {
// some code to access to a db
} catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
Related
Maybe a basic question, But I want to know, like if I have logger.error() in the try block. Does it call the catch block that is written after the try block, if the try block executes.
E.g:
try {
logger.error(String.format("No data found for pId: %s " +
"Id : %s for xyzId : %s", placeId, pId, xyzId));
System.out.println("Executed_1")
} catch (RuntimeException e) {
logger.error("Error occured while reading prices section from revision")
}
System.out.println("Executed_2")
The catch block will only be executed if a RuntimeException is thrown within the try block. If logger.error() doesn't throw that exception, then calling it will not trigger your catch block.
Will the following finally clause be executed, if an exception is thrown by the PrintWriter?
try{
PrintWriter out = new PrintWriter(filename);
try {
//output
} finally {
out.close();
}
} catch {
//handle exception
}
If the PrintWriter throws an exception, then the nested try block will never get executed, but why the nested finally clause will still be executed, even it's nested and skipped?
Updates:
I ran some tests, if an exception is thrown before the nested try clause, that nested finally will not be executed.
If the exception is thrown inside the nested try clause, then the inner finally and the outter catch will be executed.
No because the inner try block will not be reached when an exception occurs before and therefore the finally block is not reached either.
Finally block is always executed whether exception is handled or not. Even though their is an error and it reaches to catch block, it will go to finally block to execute the piece of code.
finally block is a block that is used to execute important code such
as closing connection, stream etc.
So, Inside try{} block you placed try and finally, but you asked about the catch of outside try ,thus its not going inside the first try block.That finally wont work.
P.S. : If you put finally something like this:
try{
try{...}
finally{...}
}catch(Exception e){...}
finally{... }
//in case of exception also , the outside finally is going to work.
P.S.: Though you got your answer , but the concept is for reference of other naive programmers
An uglier variant (sometimes generated by the IDE) one sees also:
// *** UGLY
PrintWriter out = null;
try {
out = new PrintWriter(filename);
//output
} catch (IOException e) {
//handle exception
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e2) {
// IGNORE
}
}
}
That explains the code a bit: as close may throw an IOException too, the code becomes cumbersome. Your code still needs nested exceptions.
With try-with-resources this can & should be written as:
try (PrintWriter out = new PrintWriter(filename)) {
//output
} catch (IOException e) {
//handle exception
} // Automatically closes.
And no longer nested exceptions.
The biggest advantage is that you need not catch any exception, and just add a throws IOException in the method signature.
I want to use a try-catch block to handle two cases: a specific exception, and any other exception. Can I do this? (An example)
try{
Integer.parseInt(args[1])
}
catch (NumberFormatException e){
// Catch a number format exception and handle the argument as a string
}
catch (Exception e){
// Catch all other exceptions and do something else. In this case
// we may get an IndexOutOfBoundsException.
// We specifically don't want to handle NumberFormatException here
}
Will the NumberFormatException be handled by the bottom block as well?
No, because the more specific exception (NumberFormatException) will be handleded in the first catch. It is important to note that if you swap the caches you will get a compilation error, since you MUST especify the more specific exceptions before the more general ones.
It is not your case, but since Java 7 you can group exceptions in catch like:
try {
// code that can throw exceptions...
} catch ( Exception1 | Exception2 | ExceptionN exc ) {
// you can handle Exception1, 2 and N in the same way here
} catch ( Exception exc ) {
// here you handle the rest
}
If a NumberFormatException is thrown, it will be caught by the first catch and the second catch won't be executed. All other exceptions go to the second.
try this: Added throw new Exception() in NFE catch.
try{
Integer.parseInt(args[1])
}
catch (NumberFormatException e){
// Catch a number format exception and handle the argument as a string
throw new Exception();
}
catch (Exception e){
// Catch all other exceptions and do something else. In this case
// we may get an IndexOutOfBoundsException.
// We specifically don't want to handle NumberFormatException here
}
In this way, You can handle NFE in its catch block. And all other in another block. You don't need to handle NFE again in second block.
I have some code thats not working(which is a common occurrence for me), but because I am not getting an errors it just continues to run with bad data. The problem I think is it keeps telling me to wrap parts of my code in try/catch blocks(my tests are basic, I just output a message in the try area and if it gets outputted I assume all went well. All does not seem well in my code). I understand in production, putting a try/catch statement helps the code to continue to run but its making me troubleshooting difficult because I'm trying to troubleshoot that section of my code.
Is there a way around this so I can actually see when something fails within the try area?
Here's a sample of my code:
try {
ByteArrayInputStream baos_back = new ByteArrayInputStream(message);
ObjectInputStream oos_back = new ObjectInputStream(baos_back);
i = oos_back.readInt();
d = oos_back.readDouble();
list_of_ints = (int[]) oos_back.readObject();
oos_back.reset();
baos_back.reset();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Are you trying to get your program to blow up when this error occurs? If so, you should be able to wrap your IOException in a RuntimeException and throw that instead. They're unchecked, so you don't need to declare them and it should kill your program just fine.
If you want your code to throw the appropriate exception, I'd suggest not using try-catch blocks at all. Try-catch is used to handle exceptions as they arise and then keep running the program, but it sounds like you don't want to handle them at all.
If you do want to use try-catch blocks you could always manually throw a RuntimeException at the end of the catch block.
Something like:
throw new IOException();
try {
// Some code...
} catch(Exception e) {
// Error handling code...
throw new RuntimeException(e.getMessage());
}
As I mentioned in my comment, you can catch all exceptions in Java with a blanket catch statement:
try {
// code
} catch (Exception e) {
e.printStackTrace();
}
This will catch every Exception thrown in the try block, and the only things it won't catch are Errors.
In practice, you will want to limit the types of exceptions you catch, and catch more specific exceptions, so you can exception chain as follows:
try {
// code
} catch (IOException ioe) {
// we expected this
ioe.printStackTrace();
} catch (SomeOtherException soe) { // just an example...
soe.printStackTrace();
} catch (Exception e) {
// Did we expect this? Maybe not!
e.printStackTrace();
}
The above also makes it known that you expect some types of exceptions to occur, and then a big blanket catch-all statement that might catch things you didn't expect.
You can also log exceptions to a file or something else, rather than output them to standard out as this code does right now. A basic logging utility is java.util.logging.
I still recommend learning to use a debugger though. Debuggers can do a lot of things like halt program execution whenever an exception is thrown, and allow you to inspect the values of variables and fields at any point in the program's execution. If you use Eclipse or Netbeans or IntelliJ or other IDEs, they have debuggers. If you use the command line, there is the jdb command-line java debugger.
I suggest editing your code generation template to do this
catch ( $ExceptionClass e )
{
// TODO: Autogenerated catch block
e.printStackTrace();
throw new RuntimeExcepton( e );
}
This way you have a TODO reminder, a barf on stdout, and are ensured that your program will blow up if you do not provide correct exception handler.
I just want to know is it necessary to put catch after try block, or can we use try blocks without a catch block?
You need to put either catch or finally block after try.
try {
}
finally {
}
or
try {
}
catch (Exception e) {
}
is it necessary to put catch after try block ?
Nope, not at all. Its not mandatory to put catch after try block, unless and until the try block is followed by a finally block. Just remember one thing, after try, a catch or a finally or both can work.
we can use try without catch block?
Yes, you can. But that will be a bad practise. Since, you are writing a try block, you should be writing catch block ( for catching the exception) and a good practise to follow it by a finally block.
Yes you can... but you must put a finally block after try. So you can do it like this:
try
{
}
finally
{
}
or
try
{
}
catch(Exception e)
{
}
Yes you can write try without catch. In that case you require finally block. Try requires either catch or finally or both that is at least one catch or finally is compulsory.
try{
// throw exception
} finally{
// do something.
}
But you should avoid this case cause in this case you will loose exception details. So if you don't want to handle it in here then simply throw that exception.
try without a catch block is a syntax error because it makes no sense (unless you also want to use a finally block). The only reason to use try is in order to catch the exception (or do a finally) from within that block
In Java 7 the try-with-resource statement doesn't need catch or finally clause
try(InputStream is = new FileInputStream(..))
{
is.read();
}
Yes you can use finally instead but to be more practical I use "throws Exception" function if I can because using try and catch blocks makes code harder to read.
First thing to remember is that you have to know what the purpose of the try-catch-finally block is.
The try block is used to test the code written inside it. If the code causes an exception, it throws the exception to the catch block.
The catch block is used to handle the thrown exception like, assume that you wrote a code that prompt the user to insert numbers only. But the user inputted a letter, thus the code throw an exception. The exception then would be caught by the catch block. Then the catch block prompt the user to re-input the data. This is what you call exception handling. But if you want to just leave the catch block empty is fine.
You may write try without the catch keyword following it but, you have to write the finally after the try block.
The code in the finally block will always be executed no matter what. You usually write codes in the finally block to close resources opened in the try block like files or database connection.
You can use the try-with-resources in place of the finally block (available in java 8).
So, you can write try followed by catch then followed by finally like the following example :
try{
//code
}
catch(Exception ex){
//code to handle the problem.
}
finally{
//Closing resources etc.
}
Or You can write this :
try{
//code
}
catch(Exception ex){
//code to handle the problem.
}
Or this :
try{
//code
}
finally{
//Closing resources etc.
}
But, you usually would want to handle the problem with the catch block.