namalfernandolk
namalfernandolk

Reputation: 9134

Why java allows run() to throw Unhanlded Exception while restricting Handled ones?

It is sayed that the run does't throw Handled Exceptions. JVM simply ignores them. So I threw UnHandled Exception (ArithmeticException). But the same thing happened for it as well. I know that it is rediculous to try to catch the excpetion from a thread that has been started by the catch clause marked as XXX. Because the excution may already passed that line.

But I wanna know why java allows run to throw Unhanlded Exception while restricting Handled ones and what is happening additionally when run() throwing Unhandled Exception?

Parent Thread

public class Parent {

    public static void main(String[] args) {

        Child   child   = new Child();
        Thread chThread = new Thread(child);

        try {
            chThread.start();

        } catch (Exception e) { // XXX mark
            System.err.println("XXX");
            e.printStackTrace();
        }

    }

Child Thread

public class Child implements Runnable {

    @Override
    public void run() throws ArithmeticException{
            method0(); // line 8
    }

    public void method0(){
        int i = 0/0; // line 12
    }
}

java.lang.Thread

public class Thread implements Runnable {
    public void run() {
    if (target != null) {
        target.run(); // line 619
    }
    }
}

StackTrace

Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero
    at seperateStacksPerThread.Child.method0(Child.java:12)
    at seperateStacksPerThread.Child.run(Child.java:8)
    at java.lang.Thread.run(Thread.java:619)

Upvotes: 0

Views: 1679

Answers (2)

Bohemian
Bohemian

Reputation: 424983

Firstly, all methods may throw unchecked exceptions.

Next, the simple reason run() doesn't throw checked exceptions is there's no one there to catch them! The method is called from within the started thread as its "main" method - it's the top level entry point. There's nothing above it to deal with an exception, so there's no point in declaring a method that throws an exceptions.

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

The signature of run() does not include a checked exception. As a result you can not override it to throw a checked exception (when you override you can never be more restrictive).
But throwing an unchecked exception is allowed as it is not part of the signature (no one is required to catch it).
When you throw the arithmetic exception it is part of the stack trace of a different thread.
Notice that it says:

Exception in thread "Thread-0" java.lang.ArithmeticException: / by zero

And not: Exception in thread "main" java.lang.ArithmeticException: / by zero

Now why are checked exceptions not allowed, it is a design decision and I think it is because no one can catch them anyway as a thread is a separate flow of excecution.

Upvotes: 1

Related Questions