What is the benefit of having two try-catch as seen below? Taken from the book Beginning Hibernate.
protected void rollback() {
try {
getSession().getTransaction().rollback();
} catch (HibernateException e) {
// TODO change to log
System.out.println(e);
}
try {
getSession().close();
} catch (HibernateException e) {
// TODO change to log
System.out.println(e);
}
}
It guarantees that close() will be invoked, even if rollback() throws an exception.
The initial purpose was to close the session even if the rollback() method throws an exception but this solutions is not good enough.
If roolback throws a RuntimeException the close code will never be called
You should do the following:
protected void rollback() {
try {
getSession().getTransaction().rollback();
} catch (HibernateException e) {
// TODO change to log
System.out.println(e);
} finally {
try {
getSession().close();
} catch (HibernateException e) {
// TODO change to log
System.out.println(e);
}
}
}
This ensures that the close code will be called no matter what.
None, really. If you replace that code with
protected void rollback() {
try {
getSession().getTransaction().rollback();
getSession().close();
} catch (HibernateException e) {
// TODO change to log
System.out.println(e);
}
}
you still get pretty much the same info. There are some minute differences:
in the first case, the line getSession().close(); will still be called even if getSession().getTransaction().rollback(); throws an exception, while in my example it will not. The proper way to handle this however is to use a finally block if you want that .close() line to be called no matter what.
The reason is independence between these parts. Both parts may fail independently. (And handled independently as well). A fail of 'rollback' invocation won't prevent execution of 'close' statement, as opposite to a single try-catch block approach for this case.
Related
I have a method, basically a loop (with all the proper catch conditions) where the exit condition is the frame being closed. This method that does something that needs an internet connection. If there isn't an internet connection it will recursively call itself until the internet connection is restored. I have noticed that after a certain amount of exceptions fired, it will simply stop to call recursively the method and therefore and no exceptions are fired after that. Is there a limit for exceptions fireable at runtime?
public Download()
{
try {
while(!frame.isWindowClosed())
{
//doSomething
}
} catch (FailingHttpStatusCodeException e) {
e.printStackTrace();
textArea.append("****** FailingHttpStatusCodeException ******\n");
new Download();
} catch (MalformedURLException e) {
e.printStackTrace();
textArea.append("****** MalformedURLException ******\n");
new Download();
} catch (IOException e) {
e.printStackTrace();
textArea.append("****** IOException ******\n");
new Download();
} catch (Exception e) {
e.printStackTrace();
textArea.append("****** Exception ******\n");
new Download();
}
}
set the try inside the loop so as long as the frame is not closed, the loop will continue. If the catch block is the same for all your Exceptions you can just catch the highest Exception:
public Download() {
while (!frame.isWindowClosed()) {
try {
// doSomething
} catch (Exception e) {
e.printStackTrace();
textArea.append("****** "+e.getClass().getName()+" ******\n");
}
}
}
As long as doSomething() did not succeeded in closing the frame the while loop will retry.
I think it's better for you to have that loop inside a method that is not inside the constructor.. Then call the method from the constructor.
I think what you should be doing is having a mechanism to check if there is network connectivity.. Then perform the required operation if there is connection. If there is no internet connectivity, then continue. You'll have to wrap this inside a while loop of course
Is it any possible way there to write catch block inside a method and call it from finally when an exception occured in try block
Ex:
try
{
int a=0,b=0;
a=b/0;
}
finally
{
callExceptions();
}
}
public static void callExceptions()
{
catch(Exception e)
{
System.out.println(e);
}
}
catch block must follow a try block. It can't stand alone.
And finally block are made to be after the catch.
You wrote an alone catch inside a finally. That doesn't make sense.
The easiest solution is to pass the exception to the method as a parameter:
public static myMethod() {
try
{
int a=0,b=0;
a=b/0;
}
catch (Exception e)
{
callExceptions(e);
}
finally
{
// do what ever you want or remove this block
}
}
public static void callExceptions(Exception e)
{
System.out.println(e);
}
Ways to uses try/catch/finally
1.- when you want to try to use some method, if everything goes well, will continue else one exception will be thrown on catch block.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
}
2.- It's the same the first but adding finally block means that the finally block will always be executed independently if some unexpected exception occurs.
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
} finally {
// some logic after try or catch blocks.
}
3.- try and finally blocks are used to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. For example:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
Referencias Official documentation JAVA for try/catch/finally blocks
On your case:
public static myMethod() {
try {
int a=0,b=0;
a=b/0;
} catch (Exception e) {
callException(e);
}
}
public static void callException(Exception e) {
System.out.println(e);
}
This was too long for a comment so sorry it's not a direct answer to your question (as others have pointed out, that's not possible). Assuming what you're trying to do is define a common way to handle your exception logic in one place, Callable might be a way to go. Something like the following might suffice... Although I'm not going to comment on whether any of it is a good idea...
static E callAndHandle(final Callable<E> callable) {
try {
return callable.call();
} catch (final Exception ex) {
System.out.println(ex);
return null;
}
}
static void tryIt() {
final String result = callAndHandle(() -> {
// Thing which might throw an Exception
return "ok";
});
// result == null => there was an error here...
}
Unfortunately Runnable doesn't declare any Exception in the signature, so if you know it always needs to be void and you don't like the return null; or similar hacks, you'd have to define your own interface to pass in.
I have a project having Exception handling written in the following way:
Parent class has all the exception handling logic. And the invoked class just throws exception and the invoker class handles with appropriate logic.
Now the problem that I am facing invoked class opens different stuffs for example, a file. These files are not getting closed at the time of exception.
so what should be the appropriate way of exception handling in this case.
class A
{
private void createAdminClient()
{
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
catch(CustomException2 e1)
{
}
catch(CustomException3 e1)
{
}
catch(CustomException4 e1)
{
}
}
}
class B
{
................
................
getClinetHandler() throws Exception
{
--------------------------
---- open a file----------
--------------------------
----lines of code---------
--------------------------
Exceptions can happen in these lines of code.
And closing file may not be called
--------------------------
---- close those files----
--------------------------
}
}
You can wrap the code which may throw an exception in a try...finally block:
getClientHandler() throws Exception {
// Declare things which need to be closed here, setting them to null
try {
// Open things and do stuff which may throw exception
} finally {
// If the closable things aren't null close them
}
}
This way the exception still bubbles up to the exception handler but the finally block ensures that the closing code still gets called in the event of an exception.
use a finally block to complete the final tasks. for example
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
finally{
// close files
}
From the doc
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
This is how I do it
try {
//What to try
} catch (Exception e){
//Catch it
} finally {
//Do finally after you catch exception
try {
writer.close(); //<--Close file
} catch (Exception EX3) {}
}
Use a finally block to handle post-processing execution (regardless whether it succeeded or failed). Like so:
// Note: as Sean pointed out, the b variable is not visible to the finally if it
// is declared within the try block, therefore it will be set up before we enter
// the block.
B b = null;
try {
b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1) {
} // and other catch blocks as necessary...
finally{
if(b != null)
b.closeFiles() // close files here
}
The finally block is always executed, regardless, even if you throw or return from the try or catch blocks.
This answer provides a very good explanation of how the finally block works in this situation, and when/how it is executed, and basically further illustrates what I just wrote.
What is the purpose of catching a FileNotFound and IOException when the FileNotFoundException is covered by IOException?
Examples:
try {
pref.load(new FileInputStream(file.getAbsolutePath()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
as opposed to:
try {
pref.load(new FileInputStream(file.getAbsolutePath()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Is it simply to enable different code to be executed if a FileNotFoundException is thrown? Or is there a different reason?
EDIT: What are a few examples of what an IOException could be thrown for? (Besides a FileNotFoundException)
It allows you to specifically handle that case. Perhaps your application needs to do something specific when a file is not found. Such as notify the user that a file was not found, rather then just a generic error.
So basically, yes, it allows different code to be executed specifically when a FileNotFoundException is thrown.
It has to, because you assigning the task for the particular FileNotFound Exception error.
If you do as IOException, user may not get the right information what went wrong in there. so doing in separate way, user come to know exactly what happening in the code.
Does the close() method of the Closeable interface get called when the Closeable object is garbage collected ? [in java 6.0]
I have a static variable which is a resource(database connection). Since this is a static resource, there's no correct place to call the close() explicitly.
The quick answer: no. GC does not care about Closeable at all.
Java does have protected void finalize() throws Throwable { } method which you can override — and it will be called on GC. It sort of works, e.g. in FileInputStream:
/**
* Ensures that the <code>close</code> method of this file input stream is
* called when there are no more references to it.
*
* #exception IOException if an I/O error occurs.
* #see java.io.FileInputStream#close()
*/
protected void finalize() throws IOException {
if ((fd != null) && (fd != FileDescriptor.in)) {
/*
* Finalizer should not release the FileDescriptor if another
* stream is still using it. If the user directly invokes
* close() then the FileDescriptor is also released.
*/
runningFinalize.set(Boolean.TRUE);
try {
close();
} finally {
runningFinalize.set(Boolean.FALSE);
}
}
}
Problem is, it creates more problems than it's worth: for example, JVM does not guarantee that it will ever call this method. That is, you should never use it for resource handling; what you see above is a safety net to make file handler leaks less damaging.
Yet another problem will be, static field will not be garbage collected—that is, as long as your class is visible. So you have no chance to use finalisation.
What you can do, though, is to use Runtime.addShutdownHook()—it will add yet another layer of safety nets to your application, giving you a chance to close the connection gracefully on exit. Given that you're using static field, the lifespan of your connection is likely to be the same as of JVM's, anyway.
I would recommend reviewing the approach, though.
Perhaps you could use finalization?
It depends on the implementation of the "Closeable" interface, how it wants to handle garbage collection. FileInputStream for example, implements the Object#finalize() method, to call the Closeable#close() method.
if you don't close the connection , it will lead to connection memory leakage; unless until application server/web server is shut down.
You can close all your connections by calling a custom close method or use finalilize
public void closeConnection {
try { rs.close(); } catch (Exception e) { // TODO Auto-generated catch block }
try { ps.close(); } catch (Exception e) { // TODO Auto-generated catch block }
try { conn.close(); } catch (Exception e) { // TODO Auto-generated catch block }
}
...
finally {
try { rs.close(); } catch (Exception e) { // TODO Auto-generated catch block }
try { ps.close(); } catch (Exception e) { // TODO Auto-generated catch block }
try { conn.close(); } catch (Exception e) { // TODO Auto-generated catch block }
}