Как работает обработчик исключений по умолчанию

1

Когда мы пытаемся запустить следующую программу, получаем ошибку: Exception in thread "main" java.lang.ArithmeticException: /by zero

class excp {
  public static void main(String args[]) {
    int x = 0;
    int a = 30/x;
  }
}

но когда мы спрашиваем кого-то, как это работает, он говорит мне, что это исключение является cautch обработчиком исключений по умолчанию. Поэтому я не мог понять, как работает этот обработчик исключений exualt. Плз это уточняет.

  • 1
    javamex.com/tutorials/exceptions/...
  • 0
    Если вы не пытаетесь / перехватываете исключение, JVM ловит его.
Теги:
exception-handling

1 ответ

3

Цитирование JLS 11:

30/x - нарушает семантическое ограничение языка Java - отсюда произойдет исключение.

If no catch clause that can handle an exception can be found, 
then the **current thread** (the thread that encountered the exception) is terminated

Перед завершением - неперехваченное исключение обрабатывается в соответствии со следующими правилами:

(1) If the current thread has an uncaught exception handler set, 
then that handler is executed.

(2) Otherwise, the method uncaughtException is invoked for the ThreadGroup 
that is the parent of the current thread. 
If the ThreadGroup and its parent ThreadGroups do not override uncaughtException, 
then the default handler **uncaughtException** method is invoked.

В твоем случае:

После исключения он переходит в класс Thread

     /**
     * Dispatch an uncaught exception to the handler. This method is
     * intended to be called only by the JVM.
     */
    private void dispatchUncaughtException(Throwable e) {
        getUncaughtExceptionHandler().uncaughtException(this, e);
    }

Затем он переходит к Threadgroup uncaugthException в соответствии с правилом 2 - поскольку ни одно исключениеHandler не определено, оно переходит к Else, если - и поток завершен

public void uncaughtException(Thread t, Throwable e) {
        if (parent != null) {
            parent.uncaughtException(t, e);
        } else {
            Thread.UncaughtExceptionHandler ueh =
                Thread.getDefaultUncaughtExceptionHandler();
            if (ueh != null) {
                ueh.uncaughtException(t, e);
            } **else if (!(e instanceof ThreadDeath)) {
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);
            }**
        }
    }

Ещё вопросы

Сообщество Overcoder
Наверх
Меню