How to catch all exceptions except a specific one? - java

Is it possible to catch all exceptions of a method, except for a specific one, which should be thrown?
void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException) {
//can I throw this to the next level without eating it up in the last catch block?
} catch (Exception e) {
//default routine for all other exceptions
}
}
/Sidenote: the marked "duplicate" has nothing to do with my question!

void myRoutine() throws SpecificException {
try {
methodThrowingDifferentExceptions();
} catch (SpecificException se) {
throw se;
} catch (Exception e) {
//default routine for all other exceptions
}
}

you can do like this
try {
methodThrowingDifferentExceptions();
} catch (Exception e) {
if(e instanceof SpecificException){
throw e;
}
}

Related

narrower catch and broader catch inside of it in Java

I have a following nested try - catch in Java as you see below.
One of my concern is that
First ( and third ) catch is InterruptedException ( and Throwable ) and we have general Exception in this catch block.
I'm wondering this exception structure makes sense or not ( ie.
narrower outside catch, and broader inside catch ).
Catch blocks don't throw an exception, it's just logging.
if this structure
is not good, is there a better way?
public void run() {
try {
} catch (InterruptedException ex) { // narrower
....
try {
...
} catch (Exception e) { // broader
...
} finally {
...
}
} catch (ShutdownSignalException shutdownException) {
try {
} catch (InterruptedException ignored) {
}
} catch (Throwable ex) {
try {
} catch (Exception e) {
}
try {
} catch (Exception e) {
} finally {
}
}}}

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.

Java handle errors & exceptions

I have a class that allows to download a file from the internet:
public String download(String URL) {
try {
if(somethingbad) {
// set an error?
return false;
}
}
//...
catch (SocketException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch(InterruptedIOException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
Now, I am calling this function in another class and i want to show a message that will help me figure out why this will not work.
what can i do to display something like this?
HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
if(r.err) {
showMessage(getMessage());
}
and the getMessage() will return the SocketException or IOException or even "empty url" if the URL is empty.
First of all I do not think you need all these:
SocketException, UnsupportedEncodingException, ClientProtocolException since they extend IOException
but if you want you can do this:
public String download(String URL) throws IOException, Exception {
try {
if(somethingbad) {
throws new Exception("My Message);
}
}
catch (IOException e) {
throw e;
}
}
And then in your other file:
try {
// some stuff
}
catch (Exception e) {
// do something with e.getMessage();
}
catch (IOException e) {
// do something with e.getMessage();
}
Instead of just doing e.printStackTrace() inside the catch blocks, throw the exception back like so:
throw e;
Then you can surround the calling code like so:
try {
HTTPReq r = new HTTPReq("http://www.stack.com/api.json");
} catch (Exception e) {
// Show error message
}

Handling the cause of an ExecutionException

Suppose I have a class defining a big block of work to be done, that can produce several checked Exceptions.
class WorkerClass{
public Output work(Input input) throws InvalidInputException, MiscalculationException {
...
}
}
Now suppose I have a GUI of some sort that can call this class. I use a SwingWorker to delegate the task.
Final Input input = getInput();
SwingWorker<Output, Void> worker = new SwingWorker<Output, Void>() {
#Override
protected Output doInBackground() throws Exception {
return new WorkerClass().work(input);
}
};
How can I handle the possible exceptions thrown from the SwingWorker? I want to differentiate between the Exceptions of my worker class (InvalidInputException and MiscalculationException), but the ExecutionException wrapper complicates things. I only want to handle these Exceptions - an OutOfMemoryError should not be caught.
try{
worker.execute();
worker.get();
} catch(InterruptedException e){
//Not relevant
} catch(ExecutionException e){
try{
throw e.getCause(); //is a Throwable!
} catch(InvalidInputException e){
//error handling 1
} catch(MiscalculationException e){
//error handling 2
}
}
//Problem: Since a Throwable is thrown, the compiler demands a corresponding catch clause.
catch (ExecutionException e) {
Throwable ee = e.getCause ();
if (ee instanceof InvalidInputException)
{
//error handling 1
} else if (ee instanceof MiscalculationException e)
{
//error handling 2
}
else throw e; // Not ee here
}
You could use an ugly (smart?) hack to convert the throwable into an unchecked exception. The advantage is that the calling code will receive whatever exception was thrown by your worker thread, whether checked or unchecked, but you don't have to change the signature of your method.
try {
future.get();
} catch (InterruptedException ex) {
} catch (ExecutionException ex) {
if (ex.getCause() instanceof InvalidInputException) {
//do your stuff
} else {
UncheckedThrower.throwUnchecked(ex.getCause());
}
}
With UncheckedThrower defined as:
class UncheckedThrower {
public static <R> R throwUnchecked(Throwable t) {
return UncheckedThrower.<RuntimeException, R>trhow0(t);
}
#SuppressWarnings("unchecked")
private static <E extends Throwable, R> R trhow0(Throwable t) throws E {
throw (E) t;
}
}
Try/multi-catch:
try {
worker.execute();
worker.get();
} catch (InterruptedException e) {
//Not relevant
} catch (InvalidInputException e) {
//stuff
} catch (MiscalculationException e) {
//stuff
}
Or with the ExecutionException wrapper:
catch (ExecutionException e) {
e = e.getCause();
if (e.getClass() == InvalidInputException.class) {
//stuff
} else if (e.getClass() == MiscalculationException.class) {
//stuff
}
}
Or if you want exceptions' subclasses to be treated like their parents:
catch (ExecutionException e) {
e = e.getCause();
if (e instanceof InvalidInputException) {
//stuff
} else if (e instanceof MiscalculationException) {
//stuff
}
}

How to deal with timeout exception in Java?

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
}

Categories