How to handle a RuntimeException in a thread

I am not sure what the best way to handle RuntimeExceptionin a thread. Let's say I have thread A, which uses a third-party function b()to send data to server S. Now it b()can throw some RuntimeException and not send data to the specified server. In this case, I need to run a method c()that transfers data to the local database. Now the method c()can also throw RuntimeExceptionif it cannot write to db.

Example:

public class A() extends Runnable {
    @Override
    public void run() {
        // throws some specific RuntimeExceptions in case it fails  
        b(data, "<some https end point>");
    } 
}

Now, if it b()does not work as expected, I need to execute the method c().

One way to handle this is to wrap b()and c()around the try-catch block and catch a RuntimeException as follows

    public void run() {
        // throws some specific RuntimeExceptions in case it fails 
        try {
        b(data, "<some https end point>");
        } catch (RuntimeException e) {
             try {
               c(data)
             } catch(RuntimeException e) {
                //Log the error
             }
        }
    } 

, . , , Future ( - ). ? , ?

+4
2

B C RuntimeException, excepetions. e.getClass().getName(), , RuntimeExceptions , .

, , "" RuntimeExcpetions, . , Exceptions, RunttimeException (, NumberFormatException), (. ). , B C .

, , . https://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html

0

, RuntimeException, . , , . , RuntimeException , .

, ( ), try-catch, , .

0

Source: https://habr.com/ru/post/1688569/


All Articles