Managing transaction across function - java

We have a java application where before this all was done in the run function of the multithreaded application. Now we are moving out some codes to a separate function. We have to make some variables as global including the connection so that it can be used in the function. Below is the skeleton of the run and calling of the function. The issue now those queries which are process in the if statement and they run into problem then the whole thing goes into catch and rollback. The problem here now is that those which are called in the processOne function and if they run into any catch the general queries which are run after if else is executed too. Is there any way to stop or linked it to the processOne error? Our idea is to use a global variable because tried the dbConn.rollback in it also it do work.
public void run() {
try{
if(){
//process here
}
else{
// call function processOne
}
//some other general queries
dbconn.commit();
}
catch (SQLException ex){
try{
dbconn.rollback();
}
catch (Exception rollback){
}
}
}
void processOne(){
try{
//process queries here
catch (SQLException ex){
try{
dbconn.rollback();
}
catch (Exception rollback){
}
}
}

All you need to do is throw an exception from processOne function, and then catch it in the 'run` function and rollback the transaction:
public void run() {
try{
if(){
//process here
}
else{
// call function processOne
}
//some other general queries
dbconn.commit();
}
catch (SQLException ex){
try{
dbconn.rollback();
}
catch (Exception rollback){
}
}
catch (Exception ex){
try{
dbconn.rollback();
}
catch (Exception rollback){
}
}
}
void processOne() throws Exception{
//process queries here
}
}
That way the entire process is rolled back.

Related

Is there a limit for exceptions fireable at runtime in java?

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

calling catch block from a method when an exception occured in try block

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.

How to catch Exceptions occured in Catch block in Java

I need to handle Exceptions which are raised by Catch block code in Java
Example, to "handle" an Exception:
try
{
// try do something
}
catch (Exception e)
{
System.out.println("Caught Exception: " + e.getMessage());
//Do some more
}
More info see: See: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
However if you want another catch in your try catch, you can do the following:
try
{
//Do something
}
catch (IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
try
{
// Try something else
}
catch ( Exception e1 )
{
System.out.println("Caught Another exception: " + e1.getMessage());
}
}
Be careful with nested try/catch, when your try catch is getting to complex/large, consider splitting it up into its own method. For example:
try {
// do something here
}
catch(IOException e)
{
System.out.println("Caught IOException: " + e.getMessage());
foo();
}
private void foo()
{
try {
// do something here (when we have the IO exception)
}
catch(Exception e)
{
System.out.println("Caught another exception: " + e.getMessage());
}
}
Instead of cascading try/catch (like in most of the other answers), I advise you to call another method, executing the required operations. Your code will be easier to maintain by this way.
In this method, put a try/catch block to protect the code.
Example :
public int classicMethodInCaseOfException(int exampleParam) {
try {
// TODO
}
catch(Exception e)
{
methodInCaseOfException();
}
}
public int methodInCaseOfException()
{
try {
// TODO
}
catch(Exception e)
{
//TODO
}
}
Do as you would do in an usual try/catch situation :
try{
throw new Exception();
}catch(Exception e1){
try{
throw new Exception();
}catch(Exception e2){
//do something
}
}
You can add new try catch block in your main catch block.
try
{
int b=10/0;
}catch(ArithmeticException e)
{
System.out.println("ArithmeticException occurred");
try
{
int c=20/0;
}catch(ArithmeticException e1)
{
System.out.println("Another ArithmeticException occurred");
}
}
I think the most clean way is to create method which is catching the exceptions occurs in its body. However it can be very dependent to the situation and type of code you are dealing with.
One example of what you are asking about is closing a Stream which is opened in a try-catch-finally block. For example:
package a;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream("temp.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
//TODO: Log the exception and handle it,
// for example show a message to the user
} finally {
//out.close(); //Second level exception is
// occurring in closing the
// Stream. Move it to a new method:
closeOutPutStreamResource(out);
}
}
private static void closeOutPutStreamResource(OutputStream out){
try {
out.close();
} catch (IOException e) {
// TODO: log the exception and ignore
// if it's not important
// OR
// Throw an instance of RuntimeException
// or one of it's subclasses
// which doesn't make you to catch it
// using a try-catch block (unchecked)
throw new CloseOutPutStreamException(e);
}
}
}
class CloseOutPutStreamException extends RuntimeException{
public CloseOutPutStreamException() {
super();
}
public CloseOutPutStreamException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CloseOutPutStreamException(String message, Throwable cause) {
super(message, cause);
}
public CloseOutPutStreamException(String message) {
super(message);
}
public CloseOutPutStreamException(Throwable cause) {
super(cause);
}
}
Here I illustrated a situation which the second level exception is occurring in the finally block, but the same can apply for the exceptions occur in the catch block.
In my point of view writing methods such as closeOutPutStreamResource can be useful because they are packaging a boiler plate code for handling very common exceptions and they are making your codes more elegant.
Also it would be your choice to catch and log the exception in closeOutPutStreamResource or to throw it to other layers of your program. But it would be more elegant to wrap this unimportant checked exceptions into RuntimeException without a need for catching.
Hope this would be helpful.
You can use try catch block any where in methods or in block, so you can write try catch in catch block as well.
try {
// master try
}catch(Exception e){
// master catch
try {
// child try in master catch
}catch(Exception e1){
// child catch in master catch
}
}//master catch
It's not necessary to have a nested try-catch block when catch block throws Exception as all answers here suggest. You can enclose the caller method with try-catch to handle that Exception.

have one handler to serve as the handler for two non-parallel 'try'

Just a short question.
I want to do something like:
try{
//Section A
....
}
catch(NumberFormatException e){
try{
//Section B
.....
}
}
catch (SQLException e){
....
}
What I want is to have catch (SQLException e) as the handler for both section A and section B. But the aforementioned way is not interpreted by javac.
How can I do it in a wise and gentle way?
One way I can think about is like following:
try{
try{
//Section A
....
}
catch(NumberFormatException e){
//Section B
.....
}
}
catch (SQLException e){
....
}
Is this the right way?
Thanks for all help.
Everything you are doing in your proposed solution is in the first try block so if a SQLException is thrown anywhere in that block it will be caught by catch (SQLException e) {}

Java: I have try,catch and finally in a java code and I want after try or catch block finally does not execute

I have following code
public class TEST
{
public static void main(String arg[]){
try
{
System.out.println("execute try");
//what should I write hear that finally does not run.
}
catch (Exception e){
System.out.println(e);
}
finally{
System.out.println("execute finally");
}
}
}
what should I write in try or catch block that finally does not run. any idea?
System.exit(0);
If you want something not to run in the "finally" block - do not put it in "finally". Finally runs always (well, except for a few cases like others have mentioned).
You need to shutdown the JVM by calling exit as:
System.exit(exit_status);
From the Java docs:
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
finally is meant to execute regardless of whether the exception occurs, period.
It can't be avoided except by resorting to dubious tactics ( as Joachim said up there ).
If the code you have in the finally block is not meant to be executed every time, don't use a finally construct; Use a simple if-construct instead
public class TEST
{
public static void main(String arg[]){
bool exitFinally = false;
try
{
System.out.println("execute try");
//what should I write hear that finally does not run.
}
catch (Exception e){
System.out.println(e);
}
finally{
if(exitFinally)
return;
System.out.println("execute finally");
}
}
}
Put the code in finally into an if.
public class TEST
{
public static void main(String arg[]){
boolean b = true;
try
{
System.out.println("execute try");
if (something()) b = false;
}
catch (Exception e){
System.out.println(e);
}
finally{
if (b){
System.out.println("execute finally");
}
}
}
}
Use boolean flag:
public class TEST
{
public static void main(String arg[]){
boolean success=false;
try
{
System.out.println("execute try");
//what should I write hear that finally does not run.
success=true;
}
catch (Exception e){
System.out.println(e);
}
finally{
if (!success)
{
System.out.println("execute finally");
}
}
}
}

Categories