java Thread 不捕获异常 默认处理逻辑

直接new Thread(()->{})默认处理逻辑
	Thread 类, 发生异常未捕获,默认JVM调用 dispatchUncaughtException 方法
    /**
     * 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);
    }

	// 线程实例的默认异常处理, 需要手动设置, 不设置默认为null
    private volatile UncaughtExceptionHandler uncaughtExceptionHandler;
    /**
     * Returns the handler invoked when this thread abruptly terminates
     * due to an uncaught exception. If this thread has not had an
     * uncaught exception handler explicitly set then this thread's
     * <tt>ThreadGroup</tt> object is returned, unless this thread
     * has terminated, in which case <tt>null</tt> is returned.
     * @since 1.5
     * @return the uncaught exception handler for this thread
     */
    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
        return uncaughtExceptionHandler != null ?
            uncaughtExceptionHandler : group;  // group就是线程对应的线程组
    }

    什么都不设置, 默认最后回来到ThreadGroup的uncaughtException 方法
    /**
     * Called by the Java Virtual Machine when a thread in this
     * thread group stops because of an uncaught exception, and the thread
     * does not have a specific {@link Thread.UncaughtExceptionHandler}
     * installed.
     * <p>
     * The <code>uncaughtException</code> method of
     * <code>ThreadGroup</code> does the following:
     * <ul>
     * <li>If this thread group has a parent thread group, the
     *     <code>uncaughtException</code> method of that parent is called
     *     with the same two arguments.
     * <li>Otherwise, this method checks to see if there is a
     *     {@linkplain Thread#getDefaultUncaughtExceptionHandler default
     *     uncaught exception handler} installed, and if so, its
     *     <code>uncaughtException</code> method is called with the same
     *     two arguments.
     * <li>Otherwise, this method determines if the <code>Throwable</code>
     *     argument is an instance of {@link ThreadDeath}. If so, nothing
     *     special is done. Otherwise, a message containing the
     *     thread's name, as returned from the thread's {@link
     *     Thread#getName getName} method, and a stack backtrace,
     *     using the <code>Throwable</code>'s {@link
     *     Throwable#printStackTrace printStackTrace} method, is
     *     printed to the {@linkplain System#err standard error stream}.
     * </ul>
     * <p>
     * Applications can override this method in subclasses of
     * <code>ThreadGroup</code> to provide alternative handling of
     * uncaught exceptions.
     *
     * @param   t   the thread that is about to exit.
     * @param   e   the uncaught exception.
     * @since   JDK1.0
     */
    public void uncaughtException(Thread t, Throwable e) {
        if (parent != null) {
            parent.uncaughtException(t, e);
        } else {
            Thread.UncaughtExceptionHandler ueh =
                Thread.getDefaultUncaughtExceptionHandler();  // 全局的异常处理器 Thread静态字段, 手动设置, 不设置默认为null
            if (ueh != null) {
                ueh.uncaughtException(t, e);
            } else if (!(e instanceof ThreadDeath)) {
                System.err.print("Exception in thread \""
                                 + t.getName() + "\" ");
                e.printStackTrace(System.err);  // 都不设置默认输出到 标准错误输出
            }
        }
    }
线程池默认处理逻辑
    ThreadPoolExecutor#runWorker 方法
    /**
     * Main worker run loop.  Repeatedly gets tasks from queue and
     * executes them, while coping with a number of issues:
     *
     * 1. We may start out with an initial task, in which case we
     * don't need to get the first one. Otherwise, as long as pool is
     * running, we get tasks from getTask. If it returns null then the
     * worker exits due to changed pool state or configuration
     * parameters.  Other exits result from exception throws in
     * external code, in which case completedAbruptly holds, which
     * usually leads processWorkerExit to replace this thread.
     *
     * 2. Before running any task, the lock is acquired to prevent
     * other pool interrupts while the task is executing, and then we
     * ensure that unless pool is stopping, this thread does not have
     * its interrupt set.
     *
     * 3. Each task run is preceded by a call to beforeExecute, which
     * might throw an exception, in which case we cause thread to die
     * (breaking loop with completedAbruptly true) without processing
     * the task.
     *
     * 4. Assuming beforeExecute completes normally, we run the task,
     * gathering any of its thrown exceptions to send to afterExecute.
     * We separately handle RuntimeException, Error (both of which the
     * specs guarantee that we trap) and arbitrary Throwables.
     * Because we cannot rethrow Throwables within Runnable.run, we
     * wrap them within Errors on the way out (to the thread's
     * UncaughtExceptionHandler).  Any thrown exception also
     * conservatively causes thread to die.
     *
     * 5. After task.run completes, we call afterExecute, which may
     * also throw an exception, which will also cause thread to
     * die. According to JLS Sec 14.20, this exception is the one that
     * will be in effect even if task.run throws.
     *
     * The net effect of the exception mechanics is that afterExecute
     * and the thread's UncaughtExceptionHandler have as accurate
     * information as we can provide about any problems encountered by
     * user code.
     *
     * @param w the worker
     */
    final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                // If pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run(); 
                    } catch (RuntimeException x) {
                        thrown = x; throw x;    // 发生异常直接抛出, 最后也会走到Thread的异常处理逻辑
                    } catch (Error x) {
                        thrown = x; throw x;  // 发生异常直接抛出 最后也会走到Thread的异常处理逻辑
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x); // 发生异常抛出 最后也会走到Thread的异常处理逻辑
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);  // 发生异常whiie循环结束  当前线程退出处理  
        }
    }
线程池的 execute 和 submit 方法异常处理 异同
    /**
     * @throws RejectedExecutionException {@inheritDoc}
     * @throws NullPointerException       {@inheritDoc}
     */
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);  // 任务被包装成FutureTask, FutureTask的run方法处理了异常, 所以如果默认task不处理异常,需要调用futureTask.get()方法获取结果或者异常,否则表象就是异常吞掉了
        execute(ftask);
        return ftask;
    }
    /**
     * Returns a {@code RunnableFuture} for the given callable task.
     *
     * @param callable the callable task being wrapped
     * @param <T> the type of the callable's result
     * @return a {@code RunnableFuture} which, when run, will call the
     * underlying callable and which, as a {@code Future}, will yield
     * the callable's result as its result and provide for
     * cancellation of the underlying task
     * @since 1.6
     */
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

    /**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }    
    FutureTask run方法
	public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);  // 异常被赋值到成员变量, 通过get方法获取结果或者异常
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }



    /**
     * Causes this future to report an {@link ExecutionException}
     * with the given throwable as its cause, unless this future has
     * already been set or has been cancelled.
     *
     * <p>This method is invoked internally by the {@link #run} method
     * upon failure of the computation.
     *
     * @param t the cause of failure
     */
    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java 全局异常处理的方法包括:采用 try-catch 块来处理异常;使用 try-with-resources 语句来声明资源;使用 finally 块来清理资源;使用 Throwable 类的 printStackTrace()方法来跟踪异常;使用 throw 关键字来抛出异常。 ### 回答2: Java有几种全局异常处理的方法。一种常见的方法是使用try-catch语句块来捕捉和处理异常。try块内编写有可能引发异常的代码,当异常发生时,程序会跳转到catch块执行相应的异常处理代码。catch块可以有多个,每个catch块用于处理不同类型的异常。这种方法通常用于局部异常处理,即在特定的代码段中处理异常。 另一种全局异常处理的方法是使用Thread类的setDefaultUncaughtExceptionHandler()方法来为所有线程设置一个默认的未捕获异常处理器。这样设置后,应用程序中的所有线程在发生未捕获异常时都会调用该处理器进行处理。这种方法适用于处理在多线程环境中发生的异常。 此外,还可以通过实现Thread.UncaughtExceptionHandler接口来自定义异常处理器。通过实现接口中的uncaughtException()方法,可以自定义异常处理逻辑,并在发生未捕获异常时进行处理。然后,通过Thread类的setUncaughtExceptionHandler()方法将自定义异常处理器设置给指定的线程。 综上所述,Java的全局异常处理方法包括使用try-catch语句块进行局部异常处理、使用setDefaultUncaughtExceptionHandler()方法为所有线程设置默认的未捕获异常处理器,以及通过实现Thread.UncaughtExceptionHandler接口来自定义异常处理器。根据具体的应用场景选择合适的方法来处理异常。 ### 回答3: Java的全局异常处理方法主要有以下几种: 1. try-catch语句块:在编写代码时,可以在可能发生异常的地方使用try-catch语句块捕获异常,然后通过catch块处理异常。这种方法适用于局部的、针对特定代码片段的异常处理。 2. throws关键字:可以在方法声明中使用throws关键字来声明可能会抛出的异常,然后在调用该方法时,使用try-catch语句块来捕获这些异常。这种方法适用于方法无法直接处理异常情况的情况下。 3. 自定义异常类:可以通过定义自己的异常类来处理特定的异常情况。通过继承Exception类或RuntimeException类,可以创建自己的异常类,并在需要抛出异常的地方使用throw关键字来抛出。 4. 异常处理器:Java提供了Thread类的setDefaultUncaughtExceptionHandler方法,可以设置默认异常处理器。通过实现Thread.UncaughtExceptionHandler接口并自定义处理方法,可以在某个线程抛出未捕获异常时进行处理。 5. AOP(面向切面编程):通过使用AOP技术,可以在代码中定义全局的异常处理切面。在抛出异常时,切面会拦截异常并进行处理。 总的来说,Java全局异常处理方法可以根据不同的场景和需求选择不同的处理方式。最佳实践是在写代码时尽量考虑到可能的异常情况,使用try-catch语句块进行局部异常处理;对于无法直接处理异常情况,可以使用throws关键字声明异常;对于特定的异常情况,可以定义自己的异常类进行处理;对于全局的异常处理,可以使用异常处理器或AOP技术。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值