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
Related
When I have a try-with-resources block like this:
try (MyIOWriter miow = new MyIOWriter() /* implements AutoCloseable */)
{
miow.write("foo"); // Might throw IOException
}
catch (IOException e) // possibly executed on close or on write
{
LOG.error("MyIOWriter failed to write something", e);
}
there's a chance the catch block is executed because the AutoCloseable MyIOWriter threw an IOException on its close method. In this case the logger message would be wrong. Is it possible to use a try-with-resources block and catch exceptions from the AutoCloseable and the block itself separately? Something like this:
try (MyIOWriter miow = new MyIOWriter() /* implements AutoCloseable */)
{
miow.write("foo"); // Might throw IOException
}
catch (IOException e) // possibly executed on write
{
LOG.error("MyIOWriter failed to write something", e);
}
finally catch (IOException e) // possibly executed on close
{
LOG.error("MyIOWriter failed to close", e);
}
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.
I have this code
root = new Root();
root.checkRootMethod2();
TextView=(TextView)view.findViewById(R.id.textView4);
if(root.checkRootMethod2()) {
TextView.setText(Html.fromHtml("<b>TEXT 01</b><br>"));
} else {
TextView.setText(Html.fromHtml("<b>TEXT 02</b><br>"));
}
try {
if (root.RootAvailibility() && (root.checkRootMethod3())) {
try {
Process process = Runtime.getRuntime().exec("su");
OutputStream stdin = process.getOutputStream();
stdin.flush();
stdin.close();
} catch(Exception e) {
}
TextView.append(Html.fromHtml(
"<b><font color=\"green\">TEXT 03</b></font>"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
root.busybox();
TextView.append(Html.fromHtml(
"<br><b><font color=\"green\">TEXT 04</b></font>"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e) {
TextView.append(Html.fromHtml(
"<br><b><font color=\"red\">TEXT05</b></font>"));
}
I wish that if if (root.RootAvailibility() && (root.checkRootMethod3())) return true Viewing a TextView that says something.If return false, another TextView that displays something else. As happens for root.checkRootMethod2 (); Same goes for root.busybox (); Do you have any idea on how I can do? Now visualize always Text04
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
/// your code ...
}
catch(Exception e){ }
TextView.append(Html.fromHtml("<b><font color=\"green\">TEXT 03</b></font>"));
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Codes here runs always regardless of if clause.
the code (try block in your case) runs regardless of the if condition as the try block clears the scope of if block.
Either put try completely inside if block or surround both if,else statement by a single try block.
I don't know what is the need of multiple try/catch here :
try {
if (root.RootAvailibility() && (root.checkRootMethod3()))
{
try
{
You can add one more catch(Exception e) to the upper try/catch block and that will serve the same purpose.
Secondly there is no else part to this if (root.RootAvailibility() && (root.checkRootMethod3())). So, if it is false the program will simply move forward.
Well you're always going to see Text04 because there's no conditional that excludes it. The try catch block it's in is at the top level.
It would help if you could provide a short, self-contained, compilable example of your code. There's clearly other potentially relevant code missing. For example, the try that goes with that last catch block. Also, it might help you to comment the beginning and end of your code blocks so that you can tell what's included in the if else statements.
Here is my code:
private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
} catch (RemoteException e) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
e.printStackTrace();
}
}
AdwordsCampaign.getAllCampaign() tries to get some remote resource. This may throw a RemoteException because the internet connection times out. When the exception is caught, I just want the thread to sleep for a while, then try to get the remote resource again.
Is there a problem with my code? Or is there a better way?
Nothing really wrong, but the (potentially infinite) retry loop with recursion (and the stack growing) makes me a little nervous. I'd write instead:
private void synCampaignWithRetries(int ntries, int msecsRetry) {
while(ntries-- >=0 ) {
try {
synCampaign();
return; // no exception? success
}
catch (ApiException e ) {
// log exception?
}
catch (RemoteException e ) {
// log exception?
}
try {
Thread.sleep(msecsRetry);
} catch (InterruptedException e1) {
// log exception?
}
}
// no success , even with ntries - log?
}
private void synCampaign() throws ApiException ,RemoteException {
List<Campaign> campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
}
This looks OK except the repetition of code in catch block(be sure of number of retries you want). You may want to create a private method to handle your exception as below:
private void synCampaign() {
List<Campaign> campaigns;
try {
campaigns = AdwordsCampaign.getAllCampaign();
for(Campaign c : campaigns)
CampaignDao.save(c);
} catch (ApiException e) {
e.printStackTrace();
waitAndSync();
} catch (RemoteException e) {
e.printStackTrace();
waitAndSync();
}
}
private void waitAndSync(){
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synCampaign();
}
You indeed cannot catch it as a SocketTimeoutException. What is possible is to catch the RemoteException, retrieve it's cause and check if that's an instanceof SocketTimeoutException.
try{
// Your code that throws SocketTimeoutException
}catch (RemoteException e) {
if(e.getCause().getClass().equals(SocketTimeoutException.class)){
System.out.println("It is SocketTimeoutException");
// Do handling for socket exception
}else{
throw e;
}
}catch (Exception e) {
// Handling other exception. If necessary
}
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.