This question already has answers here:
Is a finally block without a catch block a java anti-pattern?
(12 answers)
Closed 9 years ago.
What is the best practice in using Try Catch Finally block? Do you prefer to use only try finally block and not try catch block? I always thought that try catch finally is the best practice to use. However, in part of the code I am working with I have seen code like this:
try{
doSomething();
}
finally{
doSomethingElse();
}
Since they don't catch the exception it was really hard for me to debug the code. It wasn't a really good practice to me not using catch and only finally, but I might be wrong.
To best of my understanding, this is not really a good practice. Basically, we are not making use of what try catch was intended to be used for. I have found similar questions as well.
My questions is: "Do you agree with me on the following hypothesis: The best practice is to use try catch finally together and not try finally." If you do not agree, would you please provide me with an example of when to use try finally instead of try catch finally and why you think try finally is better than try catch?
I disagree, if you cannot do anything about an exception being thrown, but something further up your caller hierarchy can, then use the finally to clean up your resources and let the caller deal with cleaning up after the exception is thrown.
The purpose of the finally construct is to provide code that will always execute, even if an exception is thrown.
The try / finally (no catch) allows you to write code that is guaranteed to execute even if a runtime exception is thrown by the code inside the try block.
This is good in situations where you are using code that might throw runtime exceptions but does not throw checked exceptions. An example of this is Spring DAO support; which wraps IOExceptions in runtime exceptions.
Generally try-finally is used to assure that some piece of code gets executed irrespective if the exception occurs or not.
Catch block is generally missing because code in try block does not throw any checked exception which can be caught.
Eg:
try {
if(str.length() > 0) { // If str is null, it can throw NullPointer and hence code below it wont execute
// some code
}
}finally {
// Will be performed even if any unchecked exception is thrown
// Must contain code which has to be performed at any cost like releasing occupied memory
}
There are three possibilities, try+catch, try+finally, or try+catch+finally. They all have their uses.
Use the catch with try when there's something you can usefully do to handle the exception, such as report the fact that the exception has occurred.
The code inside the finally block always runs, independent of whether an exception occurs or not, so use finally with try when there's cleaning up to do that's always got to happen. An example would be closing a file if it's been successfully opened.
I do not agree.
try{}finally{} should be used in cases where you cannot handle the exception, but are required to clean up resources.
A try{}finally{} block will not cause the exception to "disappear" as you seem to think it will. It will be thrown up the stack and be handled somewhere else. If you are unable to see the exception in your current application it's because it's being thrown away elsewhere.
try {
connection = createConnection();
}
finally {
closeConnection(connection) //Free database connection.
}
In this case, you may not have any ability to handle an SQL exception, but you still want to free the database connection.
Related
This question already has answers here:
Try-catch: is this acceptable practice?
(8 answers)
Why are empty catch blocks a bad idea? [closed]
(20 answers)
Closed 9 years ago.
Say I have a try statement with and empty catch is that bad practice? For example say I have 2 try separate trys where it is possible for one to fail but the other to succeed or both succeed or any possible combination of such. Is that bad practice to handle code like that?
Example
if( mode == Modes.EDIT ){
try {user = userBo.findById(id).get(0); }
catch(Exception e) { }
try{
result = this.initializeEntityById(accountDao, id);
if( !result.equals(SUCCESS) ){
return result;
}
}
catch(Exception e){ }
}
In this example the variable in concern is 'id' where I'm not sure if the value coming in is valid and on the front end it doesn't really matter because the code handles whatever comes in and provides correct display.
So the question really is:
Is this a bad practice with the empty catch's?
Is there any potential instability that could occur that I'm not realizing?
Is there a better way to achieve what I'm looking to get at?
Yes it's always bad practice since you have no idea what went wrong where. You should at least log the exception.
The instability is that when something goes wrong, you have no idea what is wrong with your code.
It's never desirable to use exceptions for control-flow. The performance is atrocious, and exceptions should only be used for exceptional circumstances. Here's what you can do:
Make the exception part of the method signature and let a higher level handle it.
Catch the exception, but wrap it in a semantically-appropriate exception and rethrow it so a higher level can handle it.
Handle it. This can also be done in multiple ways:
Don't let the exception happen: instead of catching the exception, perform an inspection on the data to see if it can cause an exception. For example, in your case I think you should have a method like userBo.existsWithId(id) which will return a boolean that says whether the user exists. Or have the findById return null if the user cannot be found, and check to see if user == null. I think this is your best bet.
Recover from the exception in some sane way (depends on your business logic).
This is bad practice.
There's no instability, per se, but with empty catches, nothing is being done about the exception, which could leave an object in an inconsistent state if some aspects didn't get processed due to the exception.
With that said, empty catch blocks make for very difficult debugging. Even in production code, you should include a basic "notification" for most exceptions.
In testing code, use e.printStackTrace( in every catch block that does nothing otherwise.
1) Is this a bad practice with the empty catch's?
Yes this is not a good practice.
2) Is there any potential instability that could occur that I'm not realizing?
If you anything goes wrong and any exception thrown then you will not be able to identify what goes wrong because in catch block you are not doing anything so it is assumed to be handled.
3) Is there a better way to achieve what I'm looking to get at?'
Try to log the exception stacktrace in catch block . or throw it again
e.g. e.printstacktrace();
Yes, this is bad practice.
If an exception is thrown, it should be handled somehow, and the catch block is meant to hold the handling code. At the very least, if you don't need recovery code and alternate logic in your method to handle a caught exception (which would be rare), you should log the exception so you know it happened.
You can read an excellent article on handling exceptions here:
http://www.onjava.com/pub/a/onjava/2003/11/19/exceptions.html?page=2
I found the second page to be especially helpful.
I have a method throws an Exception
public int myMethod throws Exception
I have another function calls myMethod function and hava try-catch block.
I throws a runtime exception to enforce the program to be terminated.
Is this a proper way to terminate the program? If I do this way, it prints the stack trace twice and the stack trace from RuntimeException is useless.
What is the suggested way to terminate program in catch clause with printing the full stack trace.
public int callMyMethod(){
try{
myMethod();
}
catch(Exception ex){
ex.printStackTrace(System.out);
throw new RuntimeException();
}
}
The answer is "it depends".
If this code is part of the application itself then calling System.exit(int) is possibly the best option. (But if the application is "failing", then you should call exit with a non-zero return code. Zero conventionally means "succeeded".)
However, if there is a significant possibility that this code is going to be embedded / reused in a larger Java application, calling System.exit(...) is problematic. For instance a library that calls System.exit(...) when something bad happens is going to cause havoc for an application that uses it.
For something like that, you might throw a custom runtime exception which you catch and handle specifically in your main method. (If I was doing that, I'd pass the Exception as a constructor parameter to the custom exception ... and make it the cause exception. And I wouldn't print it / log it at that point.)
(Calling System.exit(...) also causes problems when you are unit testing ... 'cos the call will most likely pull the plug on the JVM running the test suite!)
The other point is that catch (Exception ...) is almost always a BAD IDEA. The point is that this catches just about everything (including all sorts of things that you never dreamed could happen!) and buries them. It is far better to catch the specific exceptions you are expecting (e.g. checked exceptions) and can deal with ... and just let the rest propagate in the normal way.
If you are stuck with catch (Exception ...) because you are using something that is declared as throwing Exception, the best way to deal with it is to change the throws Exception. And the sooner the better. Change the throws Exception to declare a list of (more) specific exceptions that you expect to be thrown by the method.
public int callMyMethod(){
try{
myMethod();
}
catch(Exception ex){
ex.printStackTrace(System.out);
System.exit(0); // terminates with exit code 0, no extra stack trace.
}
}
Exception handling is one of the most important aspects in programming.
The answer for your question depends on what type of application you are working on.
system.exit(0) will just terminate your program and this can create a lot of havoc .
Also make sure that you never catch Exception , if you are doing that then you are catching all the types of exceptions which you may not intend to handle also.
Always catch Specific exception such that it gives you opportunity to handle it in a manner which you need.
Is it considered bad programming to write a try and catch within a finally clause?
I'm having in my main method a fileInputStream which I want to close.
I want to place the .close() in the finally, so it will close no matter what. I don't want to add a throws declaration to the main method, as it is the main method :P
}finally{
try {
commandFile.close();
} catch (IOException e) {
throwException(e);
}
}
is it ok?
Thanks
The pattern of needing try/catches in finally methods is unfortunately a recurring pattern in Java 6 and before. I would argue that it actually IS a bad practice, but not one that you can really avoid in Java 6 (see below for Java 7).
An addition problem is that any new exceptions thrown in the finally block will override exceptions that were thrown before reaching this block.
In Java 7 there is specifically for the cases where resources need to be closed (the majority of the use cases for try/finally/try/catch constructs) the new try-with-resources construct. This will also capture both the primary and secondary exceptions.
Using this construct is thus now a best practice in JDK 7 and yes, the code you show is thus a bad practice in Java 7.
In one of my Java application's code, I have a try-catch-finally block in which the try block creates some input and output streams and if something goes wrong I close any earlier opened streams in finally.
finally
{
if(inputStream != null)
inputStream.close();
if(outputStream != null)
outputStream.close();
}
But the <stream>.close() line in Eclipse shows error that "Unhandled exception IOException" in the code for this line and shows that the solution is to include another try/catch in the finally block which would seem to be bad as a programming practice and I don't want in finally block.
My question is: is it possible to remove this error in Eclipse and use try/catch only when I need it instead of eclipse telling me to do the try/catch add. (Since I am already trying to avoid exception by replacing try/catch with if/else as possible).
This is not an Eclipse error, it is a Java compiler error. Eclipse is merely reporting the Java compilation error for you. There is no way to "turn it off" as the code does not compile without the try/catch clause. It is a safety feature in Java that forces you to handle commonly thrown Exceptions.
Methods have Exceptions in their signature. For example, InputStream.close() throws an IOException, forcing you to handle it in a try/catch block.
public void close() throws IOException {
...
Throwing an Exception is a way of telling the program that a significant problem - that must be handled - has occurred.
My question is: is it possible to remove this error in eclipse and use try/catch when I need it otherwise not instead of eclipse telling me to do try/catch add.
No, it is not possible.
(Since I am already trying to avoid exception by replacing try/catch with if/else as possible).
You should generally never try to replace try/catch blocks with if/else blocks. They are two distinct features with distinct purposes.
Exceptions are an essential Java feature. Read about it and understand it.
Properly this should be done something like this to ensure that we attempt to close both streams.
finally
{
try {
if(inputStream != null)
inputStream.close();
}
catch(Exception e)
{ /* Ignore */ }
try {
if(outputStream != null)
outputStream.close();
}
catch(Exception e)
{ /* Ignore */ }
}
If you don't care about handling the exception, check out the Apache commons io library.
org.apache.commons.io.IOUtils.closeQuietly(inputstream)
Works for outputstream, writer and reader too.
IOException is not something that you can avoid because it might happen because of circumstances outside your control. (Broken network connection, hard drive error etc). Eclipse is totally right that inputStream.close() and outputStream.close() itself may throw exception, and you must be prepared to handle that somehow. There is no way to silence this error because it is not Eclipse's pickiness; your code is not valid Java code as it stands.
You may declare that your function throws IOException and delegate the handling of the exception to the caller, or you must bite the bullet and handle (and probably ignore) the IOException yourself. I think there is a utility function in the IOUtils library of Apache Commons that encapsulates this logic, which would make your code cleaner (and hide the fact that you are silently ignoring an IOException).
But the .close() line in eclipse shows error that Unhandled exception IOException in code for this line and shows solution to include another try/catch in finally block which is bad as programming practice and i don't want in finally block.
The fact that close methods can also throw IOExceptions, so that you have to have nested try/catch clauses inside the finally block, is an unfortunate situation.
But there is really nothing much you can do about this. You need those (ugly) finally blocks to handle exceptions properly.
There is nothing wrong with eclipse.It just show you have a compile error in your code.you cannot replace try-catch with if-esle and here it required try catch.You need this try catch not because the input stream may be null as you try in if else.
I've been seeing code like this every now and then in PHP and I was wondering what's this all about.
$pdo = new PDO ($connect_string, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$pdo->exec ("QUERY WITH SYNTAX ERROR");
}
catch (PDOException $e) {
echo $e->getMessage();
}
What I'm interested is the catch (PDOException $e) code in general.
I var_dump the exception and it returns the PDOException class ( doh.. logical ). But that doesn't clear things what's the idea behind this technique, why it's used and what's it's name :)
I've seen this technique in Java programming also but unfortunately I don't know Java very well... :/
That is an exception handler to handle exceptions that have been thrown by $pdo->exec().
When you execute $pdo->exec(), there are possible exceptions (the code not being to function as desired) that can occur, and they are thrown (with throw new PDOException('error!') or similiar). They will be thrown as far as the first catch of their specific type.
In the example above, your catch() { ... } block will catch exceptions of PDOException. If you didn't have that block, it will bubble up to any further exception handlers, and if not handled, will crash your application. You will see some applications that have a try{ ... }/catch(){ ... } block wrapping their main request, so unhandled exceptions will bubble all the way up to it (and be handled).
If you need to have clean up code or any code that must be ran in the event of the exception being caught, you could use finally { ... } (but PHP at this stage does not support it).
If you want to change the behaviour of the exception handler, you can use set_exception_handler().
It's an error handling mechanism. If something goes wrong, an exception is thrown (in this case the exception's class is called PDOException) and in the catch part of the code you deal with the error message and possible cleaning of mess that might have occurred in try block.
you definetly should know something about OOP :)
This is the object oriented way of managing errors: in PHP (as in Java) unexpected situation (e.g. errors) are objects, exactly as anything else.
When a method (name it methodA() ) call cause some unexpected situation, instead of returning false or just terminating the program an "exception is thrown". That means that the method is interrupted, the program flow is passed to the method/function that called the "methodA()" method which have two options: thowing itself the exception or managing it.
Tha catch keywork stands for the second way: When you write some code that can maybe cause unexpected behaviour you can surround this code with a "try-catch" block, just like the example above: if the method call throw an exception object (of the type inside the catch clause) all the remaining code in the "try" block will be skipped and the code in the "catch" block will be executed. The remaining code will be executed as normal.
If you don't catch the exception you can run in different behaviour: in PHP it depends on your php.ini file, in JAVA it cause the program to end, in jsp the exception is shown in the screen and so on. Actually, in a production application you should ALWAYS catch exception when they may be thrown unless you're absolutely shure no exception will be raised.
just as a starting point have a look at this: http://php.net/manual/en/language.exceptions.php