-1

If i have 3 classes called A,B,C and all the exception are centralized in class A and A is parent class, B is child class of A and C is child class of B.now if any application defined exception occurs in class C then it throw that exception to class B and class B throws to class A to make the exception centralize.Now how can we get Exception Trace in Class A which is actually thrown by class C.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Vickys
  • 45
  • 6

3 Answers3

1

First of all, try to avoid checked exceptions if you can, for anything but those cases where you actually do something else about the exception than just abort the current unit of work and log the error.

Second, you should wrap any piece of code that emits a checked exception outside of your control with a

try { 
  ...
} catch (RuntimeException e) { throw e; } 
  catch (Exception e) { throw new RuntimeException(e); }

Otherwise, if there are no checked exceptions involved, just don't catch anything and the exception will automatically propagate upwards to your centralized handling place.

Finally, if you do as described, you will always have the original stack trace preserved: either directly in the caught exception, or in the exception that can be retrieved by .getCause(). If you just do a printStackTrace() or a log.error("error", e), you'll get the whole cause chain automatically.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

You could get the stacktrace and able to know, Throwable#getStackTrace() provides information of stacktrace in form of array of stack trace elements, each representing one stack frame.

Ans this StackTraceElement contains LineNumber, method name, class name where it got executed. So you will be able to know where it is actually thrown.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
0

Simple. Define a method which can handle exception in Parent Class A.

In derived classes,

public void method(){
    try{
      //code
    }catch(Exception e){
      super.catchExceptionMethod(e);
   }
}
RaceBase
  • 18,428
  • 47
  • 141
  • 202