Hey.

There is a method that throws an exception:

throws ClientProtocolException, ServerException, UnsecuredConnectionAttemptError, IOException{ 

How to log these exceptions to a log using log4j?

    2 answers 2

    Intercept it in catch and write to the log with the level you need.

     // в начале класса private static final Logger logger = LogManager.getLogger(<имя класса>.class); try { // код } catch(ClientProtocolException | ServerException | UnsecuredConnectionAttemptError | IOException ex) { logger.error("Что-то пошло не так", ex); throw ex; } 
    • A lot of try catch blocks work out. I thought there is an opportunity to do something differently. - Slaine
    • @Slaine wrap only the topmost method. There will be exactly one block. - Mikhail Vaysman
    • I do not understand how to do this? I have two classes, in the first several methods that throw these exceptions and the public class also throws these exceptions. - Slaine
    • @Slaine do you have a main method? Is this a desktop application? - Mikhail Vaysman
    • Yes, there is a main method. Tabletop - Slaine

    If you are actively using threads, then it is possible to suspend the exception handler on the stream. Then, if an exception occurs during operation and it is not processed, it will be possible to intercept it and do some useful work, for example, to make an entry in the log.

    It looks like this:

     Thread thread = new Thread(() -> { method(); }); thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { //логирование сообщений об ошибках } }); thread.start(); private static void method(){ // что то там кидается } 
    • Thank. But this is still too cool for me. I do not use streams. - Slaine