Does performance gets effected if unnecessary codes inside try block? - java

for sql connection we generally do like the following way
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","username","password");
As this throws exception so we generally write inside try block.But my question if i write unnecessary codes that does not throws exception with in try block then will the performance gets effected?
try
{
//some 100 lines codes that does not throw exception
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","username","password");
}
catch(Exception e)
{
}

No, at least not in any meaningful way. The biggest harm in having a "too big" try block is readability and in most cases it doesn't make sense. You could just have a throws SQLException in the method instead of a try block that spans most of the method.

Don't think so.
Its good practice to save your application from crashes.
But idea is to do not blindly use Exception but exception refer to your try{}.
In your case:
try{
//...
}
catch (ClassNotFoundException e) {
}
catch(SQLException e)
{
}

If I write unnecessary codes that does not throws exception with in try block then will the performance gets effected?
Answer is no .
Having code in try-blocks should have basically zero performance effect. The real hit comes when an exception is actually thrown.
Read these SO questions
1.Java try/catch performance, is it recommended to keep what is inside the try clause to a minimum?
2.Try Catch Performance Java

Related

Nested try blocks with catches after finally

I want to write a code like this:
try {
try {
someStuffThatCausesBusinessExceptions();
} finally {
try {
cleanUp();
} catch (Exception e) {
// I don't really care
}
}
} catch (BusinessLogicException e) {
// work with exception
// cleaning up must be done by that point (or at least tried to)
}
Will exceptions from business logic survive the possible hiatus during cleanUp? Is there a better way to ignore all the possible exceptions from cleanUp?
A catch block will only catch Throwables that were thrown in its corresponding try block. Thus, your exceptions thrown in the surrounding try block will be preserved and caught in the outer catch block.
Yes. Your exception will reach the last catch. However, this structure seems weird an non-idiomatic to me, i guess i would even prefer having cleanUp() more than once in that code over having 3 tries.
There are two cases-:
1. if excetpion occurs from mehtod someStuffThatCausesBusinessExceptions only then it will be caught in your outer catch block.
2. if the methods someStuffThatCausesBusinessExceptions and cleanUp both throw exceptions then the exception thrown from try block is suppressed.
Yes!! there is better way.You can use try-with-resources statement.
Please refere to this link.
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

Catching throwable and handling specific exceptions

Ok I know catching throwable is not a good idea:
try {
// Some code
} catch(Throwable e) { // Not cool!
// handle the exception
}
But recently I was reading through an open sourced code and I saw this interesting (at least to me) piece of code:
try {
// Some Code
} catch (Throwable ex){
response = handleException(ex, resource);
}
private handleException(Throwable t, String resource) {
if (t instanceof SQLEXception) {
// Some code
} else if (t instanceof IllegalArgumentException) {
//some code
} //so on and so forth
}
This doesn't seem to be that bad? What is wrong with this approach?
There are various reasons why you should not catch a Throwable. First of all is, that Throwable includes Errors - and there's normally not much an application can do if one of these appears. Also Throwable reduces your chances of finding out, WHAT has happened. All you get is "something bad has happened" - which might be a catastrophe or just a nuisance.
The other aproach is better but of course I still would not catch Throwable, but try to catch more specific Exceptions, if possible at all. Otherwise you are catching everything and then try to sort out which kind of bad thing happened. Your example could be written as...
try {
...
} catch (SQLEXception ex){
response = ... ;
} catch (IllegalArgumentException ex){
response = ...;
}
...which would reduce the amount of if ( ... instanceof ... ) blocks (which are only needed because the author first decided to catch everything in one big bucket). It something actually throws Throwable, then you don't have much choice, of course.
You are right when you say that catching Throwable is not a good idea. However, the code that you present in your question is not catching Throwable in an evil way but let's talk about that later. For now, the code that you present in your question has several advantages :
1. Readability
If you look at the code carefully, you will notice that even though the catch block is catching a Throwable, the handleException method is checking the type of exception thrown and possibly taking different actions based on the exception type.
The code presented in your question is synonymous to saying:
try {
doSomething();
} catch (SQLEXception ex){
response = handleException(resource);
} catch(IllegalArgumentException ex) {
response = handleException(resource);
} catch(Throwable ex) {
response = handleException(resource);
}
Even if you have to catch 10+ exceptions only, this code can easily take up a lot of lines of code and the multi-catch construct is not going to make the code any cleaner. The code that you present in your question is simply delegating the catch to another method to make the actual method that does the work more readable.
2. Reusability
The code for the handleRequest method could easily be modified and placed in a utility class and accessed throughout your application to handle both Exceptions and Errors. You could even extract the method into two private methods; One that handles Exception and one that handles Error and have the handleException method that takes a Throwable further delegate the calls to these methods.
3. Maintainibility
If you decide that you want to change the way you log an SQLExceptions in your application, you have to make this change in a single place rather than visiting every method in every class that throws an SQLException.
So is catching Throwable a bad idea?
The code that you present in your question is not really the same as catching Throwable alone. The following piece of code is a big no-no:
try {
doSomething();
} catch(Throwable e) {
//log, rethrow or take some action
}
You should catch Throwable or Exception as far away in the catch chain as possible.
Last but not the least, remember that the code you present in your question is framework's code and there are certain errors that the framework can still recover from. See When to catch java.lang.Error for a better explanation.
Catching Throwables out of laziness is a bad idea.
This was particularly tempting before try-multi-catch was introduced.
try {
...
} catch (SomeException e) {
//do something
} catch (OtherException e) {
//do the same thing
} ...
Repeating catch blocks is tedious and verbose, so some people decided to just catch Exception or Throwable and be done with it. This is what should be avoided because:
It makes it difficult to follow what you're trying to do.
You may end up catching a lot of stuff you can't deal with.
You deserve bonus punishment if you completely swallow the Throwable in the catch block. (And we've all seen code that does that...:))
But catching Throwables when it is absolutely necessary is fine.
When is it necessary? Very rarely. In framework-style code there are various scenarios (dynamically loading an external class is the most obvious one), in a standalone application a typical example is to attempt to display/log some kind of error message before exiting. (Bearing in mind that the attempt may fail, so you don't want to put anything critical there.)
As a rule of thumb, if there's nothing you can do about an exception/error, you shouldn't catch it at all.
You posted a link to Jongo, which demonstrates one possible use for this technique: re-using error handling code.
Let's say you've got a large block of error handling code that naturally repeats itself in various places in your code - for example Jongo produces standard responses for some standard classes of errors. It may be a good idea to extract that error handling code into a method, so you can re-use it from all the places it's needed.
However, that's not to say that there's nothing wrong with Jongo's code.
Catching Throwable (rather than using multicatch) is still suspicious, as you're likely to catch Errors that you're not really in a position to handle (are you sure you meant to catch ThreadDeath?). In this situation, if you absolutely have to catch Throwable, it'd be better to "catch and release" (i.e, rethrow anything that you didn't mean to catch). Jongo doesn't do this.
There are exactly two valid uses for using a huge net:
If you will handle everything uniformly, like a top-level catch for logging/reporting, possibly followed by an immediate exit.
To reduce duplication, by exporting all the handling into its own method.
Catch the most derived common ancestor there is to avoid extra-work and increase clarity.
DRY is an important design principle.
In both cases, unless you expected that exception and handled it completely, rethrow.
First of all, catching Throwable makes your application rather intransparent. You should be as explicit as possible on catching exceptions to enable good traceability in exceptional cases.
Let's have a look at the method handleException(...) and see some of the problems that occur by this approach:
you catch Throwable but you only handle Exceptions, what happens if an e.g. OutOfMemoryError of type Error is thrown? - I see bad things to happen...
Regarding good object oriented programming using instanceof breaks the Open-Closed-Principle and makes code changes (e.g. adding new exceptions) really messy.
From my point of view, catch-blocks are exactly made for the functionality that are tried to cover in handleExceptions(...), so use them.
Java 7 solves a bit of the tedium that is multi-catching of similar exceptions with similar handling. You definitely should not be doing what the person has done here. Just catch the appropriate exceptions as needed, it may look ugly but then that's what throws is for, pass it to the method that should catch it and you shouldn't be wasting too much code space.
Check out this link for more information.
Just to provide balance - there is one place where I will always catch (Throwable):
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
At least something shows somewhere that something went wrong.
You can always catch different type of exceptions and perform some operations based on the type of the exception you got.
Here is an example
try{
//do something that could throw an exception
}catch (ConnectException e) {
//do something related to connection
} catch (InvalidAttributeValueException e) {
// do anything related to invalid attribute exception
} catch (NullPointerException e) {
// do something if a null if obtained
}
catch (Exception e) {
// any other exception that is not handled can be catch here, handle it here
}
finally{
//perform the final operatin like closing the connections etc.
}

Java - How can I avoid using try catch statements

I would like to know how I can avoid try-catch statements. Right now I have a Database handler and every time I run a command I have to surround it in a try block like so:
try {
while(levelData.next()) {
if(levelData.getInt("level") == nextLevel) return levelData.getInt("exp");
}
} catch (SQLException e) {
e.printStackTrace();
}
Can I make it so the actual function throws the exception or something? Rather than having to manually put all these try's in? Its mostly just an aesthetic problem as these try blocks look ugly.
You can throw an exception instead:
public void myMethod() throws SQLException {
while(levelData.next()) {
if(levelData.getInt("level") == nextLevel)
return levelData.getInt("exp");
}
}
Right now I have a Database handler and every time I run a command I
have to surround it in a try block like so...
I think other answers fail to address the above problems. When I started programming with Java, I hated it when my program was filled with try-catch blocks for SQL query statements.
The way I work around it is to use a DAO-level-layer to handle the exceptions. For example, If my program need to access a User table, I create a UserDAO class. Then the queries are created and exceptions are caught in that DAO class.
Every time an exception occurs, I do the logging needed and throw a custom-specified Unchecked Exception, e.g. DatabaseErrorException. The main difference between an unchecked exception and a checked exception (like SQLException) is that you aren't forced to catch or throw it, so it will not fill your code with the throws statement.
(Yes, you can use throws to avoid using try-catch, but you must handle it somewhere anyway, and think about your functions having throws everywhere.)
Then we can have a global filter at the highest level of the application to catch all these exceptions which propagate through the program. Usually a database error can't be recovered from, so here we only need to display the error to the users.
You can make a method throw an exception with the throws keyword, rather than using a try- catch block, but at some point the exception needs to be handled. What I have found most annoying is multiple catch statements, but if you use JDK >= 1.7 they have a multi-catch option available. For exception logging you can use the log4j library.

How do you continue your program even if an exception occurs?

In my program I have to constantly access the hard drive thousands of times to view images (no way around it), occasionally my program gets tripped up on a "file not found IO Exception" most likely because of the many modifications I'm making to the images and re saving quickly. How do I continue my program even if this error occurs, because currently it causes my program to stop?
Code:
filepattern=imageLocation+temp+"image.jpg";
File outputfile = new File(filepattern);
BufferedImage img = null;
try {
img = ImageIO.read(outputfile);
} catch (IOException e) {
}
Note: I have fixed the problem by making sure the file exists first. Thanks for all your help!
Catch the exception and handle it as needed.
try {
// your code
} catch (<Expected exception> e) {
// handle the exception
}
Surround the statement with a try catch.
This will stop the code from crashing and in the catch block you can write code to deal with the failure.
There are 3 key words
try {}
executes the block that can cause problems
catch (Exception ex) {}
executes code to handle specific exceptions. Instead of Exception you can handle specific exception types
finally {}
executes cleanup code. Even if exception occurs and breaks the execution flow in try block, this code will always execute.
You might try something like the fragment below. Of course, you will want to encapsulate the actual reading in a try / catch / finally block to make sure you close the file
try {
filesTried++;
[you code]
} catch (IOException e) {
fileErrors++;

Why use finally instead of code after catch [duplicate]

This question already has answers here:
Why do we use finally blocks? [duplicate]
(11 answers)
Closed 5 years ago.
Why do this
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
cs.close();
rs.close();
}
Instead of this
} catch (SQLException sqle) {
sqle.printStackTrace();
}
rs.close();
cs.close();
Because if an exception gets thrown no code after the try block is executed unless the exception is caught. A finally block is always executed no matter what happens inside your try block.
Look at your catch block - it's going to throw DAOException. So the statements after your catch block aren't going to be executed even in the sample you've given. What you've shown (wrapping one exception in another) is one common pattern - but another possibility is that the catch block "accidentally" throws an exception, e.g. because one of the calls it makes fails.
Additionally, there may be other exceptions you don't catch - either because you've declared that the method throws them, or because they're unchecked exceptions. Do you really want to leak resources because an IllegalArgumentException got thrown somewhere?
Because if an exception is thrown,
Code in the finally clause will execute as the exception propagates outward, even if the exception aborts the rest of the method execution;
Code after the try/catch block will not get executed unless the exception is caught by a catch block and not rethrown.
According to HeadFirst Java, a finally block will run even if the try or catch block has a return statement. Flow jumps to finally and then back to return.
Because it ensures that the stuff in the finally block gets executed. Stuff after catch might not get executed, say, for example, there is another exception in the catch block, which is very possible. Or you just do what you did, and throw an exception wrapping the original exception.
The finally keyword guarantees that the code is executed. In your bottom example, the close statements are NOT executed. In the top example, they are executed (what you want!)
Your second approach won't do the 'close' statements because it is already left the method.
This is the way to avoid resource leaks
If you catch all errors, there should no difference, otherwise, only code inside finally block is executed because the code execution sequence is:
finally code -> error throw -> code after catch
hence, once your code throw any unhandled error, only finally code block works as expected.
The code in the finally block will get called before the exception is rethrown from the catch block. This ensures that any cleanup code that you've put in the finally block gets called. Code outside of the finally block will not be run.
this might clarify: http://www.java2s.com/Code/Java/Language-Basics/Finallyisalwaysexecuted.htm
consider the catch can throw an exception to the higher level functions in the call stack. This will lead calling final before throwing the exception to the upper level.
In http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html this is misleading (and may have originated the question):
The try block of the writeList method that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeList method. This poses a somewhat complicated problem because writeList's try block can exit in one of three ways.
1. The new FileWriter statement fails and throws an IOException.
2. The list.get(i) statement fails and throws an IndexOutOfBoundsException.
3. Everything succeeds and the try block exits normally.
The 4th way (an exception other than IOException and IndexOutOfBoundsException is thrown) is missing. The code depicted in the preceding page only catches (1) and (2) before resorting to finally.
I'm also new to Java and had the same questioning before finding this article. Latent memory tend to attach itself more to examples than to theory, in general.
The finally block may not always run, consider the following code.
public class Tester {
public static void main(String[] args) {
try {
System.out.println("The main method has run");
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("The finally block has run");
}
}
}
In your case, I would suggest to wrap the code inside finally block into try/catch, as this code apparently may throw an exception.
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
cs.close();
rs.close();
} catch (Exception e) {
//handle new exception here
}

Categories

Resources