java.lang.Thread.setDefaultUncaughtExceptionHandler()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.6k)|赞(0)|评价(0)|浏览(192)

本文整理了Java中java.lang.Thread.setDefaultUncaughtExceptionHandler()方法的一些代码示例,展示了Thread.setDefaultUncaughtExceptionHandler()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Thread.setDefaultUncaughtExceptionHandler()方法的具体详情如下:
包路径:java.lang.Thread
类名称:Thread
方法名:setDefaultUncaughtExceptionHandler

Thread.setDefaultUncaughtExceptionHandler介绍

[英]Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Uncaught exception handling is controlled first by the thread, then by the thread's ThreadGroup object and finally by the default uncaught exception handler. If the thread does not have an explicit uncaught exception handler set, and the thread's thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler's uncaughtException method will be invoked.

By setting the default uncaught exception handler, an application can change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that would already accept whatever "default" behavior the system provided.

Note that the default uncaught exception handler should not usually defer to the thread's ThreadGroup object, as that could cause infinite recursion.
[中]设置当线程由于未捕获异常而突然终止时调用的默认处理程序,并且尚未为该线程定义其他处理程序。
未捕获异常处理首先由线程控制,然后由线程的ThreadGroup对象控制,最后由默认的未捕获异常处理程序控制。如果该线程没有显式的uncaughtException处理程序集,并且该线程的线程组(包括父线程组)没有专门化其uncaughtException方法,则将调用默认处理程序的uncaughtException方法。
通过设置默认的未捕获异常处理程序,应用程序可以更改那些已经接受系统提供的任何“默认”行为的线程处理未捕获异常的方式(例如记录到特定设备或文件)。
请注意,默认的未捕获异常处理程序通常不应遵从线程的ThreadGroup对象,因为这可能会导致无限递归。

代码示例

代码示例来源:origin: libgdx/libgdx

public void create () {
  Thread.setDefaultUncaughtExceptionHandler(exHandler);
}

代码示例来源:origin: alibaba/canal

private static void setGlobalUncaughtExceptionHandler() {
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
      logger.error("UnCaughtException", e);
    }
  });
}

代码示例来源:origin: apache/storm

public static void setupDefaultUncaughtExceptionHandler() {
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread thread, Throwable thrown) {
      try {
        handleUncaughtException(thrown);
      } catch (Error err) {
        LOG.error("Received error in main thread.. terminating server...", err);
        Runtime.getRuntime().exit(-2);
      }
    }
  });
}

代码示例来源:origin: stackoverflow.com

if(!(Thread.getDefaultUncaughtExceptionHandler() instanceof CustomExceptionHandler)) {
  Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
      "/sdcard/<desired_local_path>", "http://<desired_url>/upload.php"));
}

代码示例来源:origin: square/okhttp

@Override public void testRunFinished(Result result) throws Exception {
  Thread.setDefaultUncaughtExceptionHandler(oldDefaultUncaughtExceptionHandler);
  System.err.println("Uninstalled aggressive uncaught exception handler");

  synchronized (exceptions) {
   if (!exceptions.isEmpty()) {
    throw Throwables.rethrowAsException(exceptions.keySet().iterator().next());
   }
  }
 }
}

代码示例来源:origin: Netflix/zuul

private ServerGroup(String name, int acceptorThreads, int workerThreads, EventLoopGroupMetrics eventLoopGroupMetrics) {
  this.name = name;
  this.acceptorThreads = acceptorThreads;
  this.workerThreads = workerThreads;
  this.eventLoopGroupMetrics = eventLoopGroupMetrics;
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(final Thread t, final Throwable e) {
      LOG.error("Uncaught throwable", e);
    }
  });
  Runtime.getRuntime().addShutdownHook(new Thread(() -> stop(), "Zuul-ServerGroup-JVM-shutdown-hook"));
}

代码示例来源:origin: square/okhttp

@Override public void testRunStarted(Description description) {
 System.err.println("Installing aggressive uncaught exception handler");
 oldDefaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
 Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
  StringWriter errorText = new StringWriter(256);
  errorText.append("Uncaught exception in OkHttp thread \"");
  errorText.append(thread.getName());
  errorText.append("\"\n");
  throwable.printStackTrace(new PrintWriter(errorText));
  errorText.append("\n");
  if (lastTestStarted != null) {
   errorText.append("Last test to start was: ");
   errorText.append(lastTestStarted.getDisplayName());
   errorText.append("\n");
  }
  System.err.print(errorText.toString());
  synchronized (exceptions) {
   exceptions.put(throwable, lastTestStarted.getDisplayName());
  }
 });
}

代码示例来源:origin: stackoverflow.com

public class ForceClose extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

    setContentView(R.layout.main);
  }
}

代码示例来源:origin: aa112901/remusic

public void initCatchException() {
  //设置该CrashHandler为程序的默认处理器
  UnceHandler catchExcep = new UnceHandler(this);
  Thread.setDefaultUncaughtExceptionHandler(catchExcep);
}

代码示例来源:origin: stackoverflow.com

public class BaseActivity extends Activity{
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      @Override
      public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
        Log.e("Alert","Lets See if it Works !!!");
      }
    });
  }
}

代码示例来源:origin: alibaba/jstorm

public static void main(String[] args) throws Exception {
  LOG.info("Begin to start drpc server");
  Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
  final Drpc service = new Drpc();
  service.init();
}

代码示例来源:origin: Tencent/tinker

@Override
protected void attachBaseContext(Context base) {
  super.attachBaseContext(base);
  Thread.setDefaultUncaughtExceptionHandler(new TinkerUncaughtHandler(this));
  onBaseContextAttached(base);
}

代码示例来源:origin: Netflix/zuul

private ServerGroup(String name, int acceptorThreads, int workerThreads, EventLoopGroupMetrics eventLoopGroupMetrics) {
  this.name = name;
  this.acceptorThreads = acceptorThreads;
  this.workerThreads = workerThreads;
  this.eventLoopGroupMetrics = eventLoopGroupMetrics;
  Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(final Thread t, final Throwable e) {
      LOG.error("Uncaught throwable", e);
    }
  });
  Runtime.getRuntime().addShutdownHook(new Thread(() -> stop(), "Zuul-ServerGroup-JVM-shutdown-hook"));
}

代码示例来源:origin: alibaba/jstorm

/**
   * start supervisor daemon
   */
  public static void main(String[] args) {
    Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
    JStormServerUtils.startTaobaoJvmMonitor();
    Supervisor instance = new Supervisor();
    instance.run();
  }
}

代码示例来源:origin: ReactiveX/RxJava

try {
  CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler();
  Thread.setDefaultUncaughtExceptionHandler(handler);
  IllegalStateException error = new IllegalStateException("Should be delivered to handler");
  Flowable.error(error)
  Thread.setDefaultUncaughtExceptionHandler(originalHandler);

代码示例来源:origin: ReactiveX/RxJava

private static void expectUncaughtTestException(Action action) {
  Thread.UncaughtExceptionHandler originalHandler = Thread.getDefaultUncaughtExceptionHandler();
  CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler();
  Thread.setDefaultUncaughtExceptionHandler(handler);
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override
    public void accept(Throwable error) throws Exception {
      Thread.currentThread().getUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), error);
    }
  });
  try {
    action.run();
    assertEquals("Should have received exactly 1 exception", 1, handler.count);
    Throwable caught = handler.caught;
    while (caught != null) {
      if (caught instanceof TestException) { break; }
      if (caught == caught.getCause()) { break; }
      caught = caught.getCause();
    }
    assertTrue("A TestException should have been delivered to the handler",
        caught instanceof TestException);
  } catch (Throwable ex) {
    throw ExceptionHelper.wrapOrThrow(ex);
  } finally {
    Thread.setDefaultUncaughtExceptionHandler(originalHandler);
    RxJavaPlugins.setErrorHandler(null);
  }
}

代码示例来源:origin: ReactiveX/RxJava

CapturingUncaughtExceptionHandler handler = new CapturingUncaughtExceptionHandler();
CapturingObserver<Object> observer = new CapturingObserver<Object>();
Thread.setDefaultUncaughtExceptionHandler(handler);
IllegalStateException error = new IllegalStateException("Should be delivered to handler");
Flowable.error(error)
Thread.setDefaultUncaughtExceptionHandler(originalHandler);

代码示例来源:origin: alibaba/jstorm

public static void main(String[] args) throws Exception {
  Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
  // read configuration files
  @SuppressWarnings("rawtypes")
  Map config = Utils.readStormConfig();
  JStormServerUtils.startTaobaoJvmMonitor();
  NimbusServer instance = new NimbusServer();
  INimbus iNimbus = new DefaultInimbus();
  instance.launchServer(config, iNimbus);
}

代码示例来源:origin: chewiebug/GCViewer

@Override
  public void run() {
    new GCViewerGuiBuilder().initGCViewerGui(gcViewerGui, modelLoaderController);
    applyPreferences(gcViewerGui, new GCPreferences());
    gcViewerGui.addWindowListener(GCViewerGuiController.this);
    Thread.setDefaultUncaughtExceptionHandler(new GCViewerUncaughtExceptionHandler(gcViewerGui));
    gcViewerGui.setVisible(true);
  }
};

代码示例来源:origin: robolectric/robolectric

@Test
public void shouldQuitLooperAndThread() throws Exception {
 handlerThread = new HandlerThread("test");
 Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
 handlerThread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
 handlerThread.start();
 assertTrue(handlerThread.isAlive());
 assertTrue(handlerThread.quit());
 handlerThread.join();
 assertFalse(handlerThread.isAlive());
 handlerThread = null;
}

相关文章