Is there a way to handle the exception globally in Java?

In C #, we can call a method that takes a function or action and does it in a try catch. By doing this, we can handle all exceptions in one place, making it more manageable.

Since Java has no delegates, this cannot be accomplished the same way. Is there any alternative?

We have 2 classes: A and B. B is subclass A. All methods from B override those from A.

Should I handle all my exceptions in methods in B or is there a way to handle it in and just reverse engineer in B? My guess is that I should be handling the whole thing in B, but I want to confirm this.


source to share

2 answers

C # delegates are not essential to what you are describing and they are just another way to pass references to arbitrary functions. The same offers simple vanilla objects through the polymorphism feature.

In classic Java, you can bypass implementations Runnable

or Callable

, and you can provide implementations such as anonymous classes. In Java 8, you can provide implementation with the lambda syntax.

public static void runWithExceptionHandling(RunnableExc r) {
   try {; } 
   catch (xxxException e) { ... }

public static void main(String[] args) {
   runWithExceptionHandling(() -> Files.readAllLines(Paths.get("/x/y"), UTF_8));
   runWithExceptionHandling(() -> { throw new xxxException(); });

interface RunnableExc { void run() throws Exception; }




Thread.setDefaultUncaughtExceptionHandler (UncaughtExceptionHandler eh) does roughly what you are looking for



All Articles