I need to handle all the errors in one class (in fact - not all, but it does not matter).


Processing should occur so that the handler itself redirects the error to the desired class:

try { //Ошибка } catch (Exception e) { handleError(e); //Передается в нужный класс (обработчик) } 

I found two solutions:

  1. Call the static class method ErrorHandler.handle(e) .

  2. Import the same static class method with a static import and call handle(e) immediately.

Only in both cases there is a direct link to the class, which is undesirable.


Is there any way to centrally handle errors so that one class receives them? I wanted to consider the option with the logger, but did not find such a logger to get errors in a certain class.

  • 2
    You can wrap all the code from main in try / catch, and add all the other classes and methods to throws. But on the whole - this is some sort of pornography - rjhdby

1 answer 1

There is a way to intercept all the raw errors in the stream. First we make a class that implements UncaughtExceptionHandler

 public class TryMe implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread thread, Throwable throwable) { Log.d("TryMe", "Something wrong happened!"); } } 

Where we write the processing algorithm.

And then in the right thread we write the following.

 Thread.setDefaultUncaughtExceptionHandler(new TryMe()); 

And everything that is not handled by try/catch will fall into this class. PS And since this is an interface with one method, you can pack everything into a lambda.

 Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {Log.d("TryMe", "Something wrong happened!");});