-1

I got this method:

public void foo(){
    int test = 5/0;
}

And I call it like this:

try {
    foo();
} catch (Exception e){
    e.printStackTrace();
}

This catches the ArithmeticException, but I have seen cases where I call a method inside try-catch, but it doesn't catch the exception. Is there a specific situation in which the exception may not be caught?

Here is an example to clarify the question: Does the try-catch block in ActivityA catches the exception in ActivityB? I know the answer is negative. But I want to know the logic behind this.

public class ActivityA extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_a);
            startActivity(new Intent(this, ActivityB.class));
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

And ActivityB:

public class ActivityB extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
        int x = 5/0    
    }
}

To all cool guys who think this is a duplicate question, please give me a link to a question on StackOverFlow that answers to this very clear question: Does a try-catch catches exceptions that happens in a method which is called inside it?

saraX
  • 181
  • 2
  • 13
  • Possible duplicate of [Best practices in handling java exceptions](https://stackoverflow.com/questions/7803110/best-practices-in-handling-java-exceptions) – Marek J Dec 13 '17 at 10:28
  • Try to specify the Exception like `IllegalArgumentException`. – F0XS Dec 13 '17 at 10:29
  • Please [edit] your question and explain which cases you have seen where the exception is thrown but not caught. What method were you calling? What does the method do? Are you sure it throws an exception? How do you know? – RealSkeptic Dec 13 '17 at 10:31
  • Possible duplicate of [How should I throw a divide by zero exception in Java without actually dividing by zero?](https://stackoverflow.com/questions/1657887/how-should-i-throw-a-divide-by-zero-exception-in-java-without-actually-dividing) – F0XS Dec 13 '17 at 10:31
  • @RealSkeptic If I had access to those cases, I wouldn't ask the question here. I'd analyse it by myself. But it was a long time ago. So I am asking here to find any possible cases! – saraX Dec 13 '17 at 10:36
  • 2
    So your question is about a memory of long time ago, of unspecified circumstances, without any code to look at? No, that's not a proper question for StackOverflow. – RealSkeptic Dec 13 '17 at 10:37
  • It's not a duplicate question @foxdie . It takes a few seconds to read the question carefully and judge! – saraX Dec 13 '17 at 10:48
  • Please read the question more carefully! That's a duplicate??? @MarekJeszka – saraX Dec 13 '17 at 10:49

4 Answers4

0

What may have happened is that you tried to catch in an exception that was not the one that was fired. In the case of ArithmeticException, if you fire one, for example, NumberFormatException, it won't hold the Exception and will stop your application.

KL_
  • 1,503
  • 1
  • 8
  • 13
0

If you catch Exception, Exception itself and all exceptions that are a subtype of Exception will be caught by that block. In Java that will be the so called "checked exceptions".

However, you will not catch those "exceptions" that are only a subtype of Throwable. To be precise, those are not acctually exceptions. They are errors. It is also possible to catch them in a try-catch statement.

Not that neither catching Exception nor Throwable is a good practice. Always catch the specific exceptions and errors you are expecting.

André Stannek
  • 7,773
  • 31
  • 52
  • So if I call a methods inside try-catch that in turn calls another method, can I say the try-catch catches all the exceptions even if it happens inside farthest called methods? – saraX Dec 13 '17 at 10:46
  • @saraX basically yes. It catches exceptions from all calls inside the `try` block. If an exceptions is not caught, it is thrown up the call hierachy until it is caught somewhere (or crashes the program if it's not caught anywhere). – André Stannek Dec 13 '17 at 10:49
  • So if I put all the code inside my `onCreate()` method, it catches all the exceptions in my app because it's the start point in my app and all other stuff are called from inside it? – saraX Dec 13 '17 at 10:57
  • @saraX if it's not caught beforehand: yes – André Stannek Dec 13 '17 at 10:59
0

If you specify an exception to be caught, e.g

public void foo(numb, divisor) throws ArithmeticException {
    if (divisor == 0) throw new ArithmeticException();
    int ans = num / divisor;
}

@Test
public void tesfooWithZeroDivisor() {
    try {
        foo(5, 0);
    } catch (ArithmeticException e) {
        System.out.println("Can't divide by zero");
    }

}

In this case, you're specifying that you want an ArithmeticException to be caught if thrown. In the event that no ArithmeticException is thrown but a different exception such as IllegalArgumentException, then it will not catch an IllegalArgumentException because you only specify ArithmeticException.

In your case, you used catch (Exception e) which means you didn't specify an exception so it will catch any exception that got thrown regardless.

Daini Sani
  • 21
  • 3
0

Is there a specific situation in which the exception may not be caught?

Some situations spring to mind:

  • The code (e.g. the call to foo()) was not executed. So the exception was not thrown.
  • The exception was thrown by different code; e.g. in your example, the foo() method is called from somewhere else; e.g. on a different thread stack.
  • The exception was caught further up the call chain.
  • You have declared your own exception (e.g. my.pkg.ArithmeticException) and you are catching a different exception to the one thrown as a result
  • If you do funky things with classloaders, it is possible to load the same class more than once. If you do that, you will have types that have the same name, but are in fact different. If you did that with an exception class, the instanceof test that the handler performs may fail to match.

Does a try-catch catches exceptions that happens in a method which is called inside it?

Yes. If you have implemented it properly; see above.

If you want chapter and verse, read JLS 14.20.


Concerning your updated example, I would not expect the exception handler for ActivityA to see exceptions thrown in ActivityB.onCreate. I would expect onCreate() to be called by a different thread.

You can confirm this by catching the exception in ActivityB.onCreate and looking at the stacktrace.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • According to one of answers, if I put all the code inside my `onCreate()`method, it catches all the exceptions in my app because it's the start point in my app and all other stuff are called from inside it. Yes? what if I use an intent to another activity inside a try-catch block? Does it mean all the exceptions inside the new `Activity` are caught? @stephen-c – saraX Dec 13 '17 at 11:05
  • Give us a specific example. But in general the answer is No. The fact that code is lexically "inside" your `onCreate()` doesn't necessarily mean that it will be executed by the thread that calls your `onCreate()` method. There are all sorts of ways to get code to run on a different stack in Android. – Stephen C Dec 13 '17 at 11:09
  • Well, I edited the question and added some code block to give you a specific example. I'd appreciate if you guide me through this. @stephen-c – saraX Dec 13 '17 at 12:01