7

If you run following code then it will compile and run successfully,

public class Example { public static void main(String[] args) { // insert code here try { new Example().go(); // throw new OutOfMemoryError(); } catch (Error e) { System.out.println(e); } } void go() { go(); } } 

With following output :

java.lang.StackOverflowError 

So my question is "Can we catch an Error"..??

3
  • 1
    We can catch an error, yes Commented Feb 3, 2015 at 9:45
  • 1
    catch Throwable it will catch both exception and error. But seriously its not a good practice. U should fix asap as soon as there is error in your code. To print in catch block use System.out.err("java.lang.StackOverflowError"); Commented Feb 3, 2015 at 9:45
  • 3
    your code just did. it even printed out your error, see? Commented Feb 3, 2015 at 9:46

4 Answers 4

6

Answer to your question is yes, you can catch error in java. And your code is almost correct. Your method go() calls itself infinitely and therefore causes StackOverflowError that is caught in your catch block and printed by System.out.println()

Sign up to request clarification or add additional context in comments.

Comments

4

Yes, you can catch an Error, but you are advised not to do it, since Errors indicate serious problems that a reasonable application should not try to catch. (as stated in the Javadoc of Error)

Comments

3

Yes, we can catch an error.

The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the throw statement.

Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purpose of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.

try { while(true) { } } catch (Throwable e) { // TODO: handle exception System.out.println(e); } 

Comments

2

Note that there's a difference between StackOverflowException and StackOverflowError, since you have an error, it's a serious indication that you should never try to catch it.

Just don't do infinite things in your code, when this error happens, no stack space is available, how would you want to proceed?

StackOverFlowError indicates that you have severe problems, it's a bad idea to catch this error, instead, try to understand what problems you have in your code and fix them.

1 Comment

There is nothing called StackOverflowException. There is only StackOverflow error

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.