Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw Exceptions with custom stack trace

Is it possible to throw an exception (could be any exception) with a customized stack trace?

As a concrete example: lets say I have a set of some small static utility methods which might throw exceptions. However I would like the exception to appear to have originated from the previous method instead of the utility method (I want to ignore the 1st frame of the trace).

like image 476
Joseph Daigle Avatar asked May 26 '09 19:05

Joseph Daigle


People also ask

Can we use throws for custom exception?

The throw keyword is useful for throwing exceptions based on certain conditions e.g. if a user enters incorrect data. It is also useful for throwing custom exceptions specific to a program or application. Unchecked exceptions can be propagated in the call stack using the throw keyword in a method.

How do I print a stack trace for exceptions?

Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception. Using getMessage() method − Mostly used. It prints the description of the exception.

What is stack trace exception?

A trace of the method calls is called a stack trace. The stack trace listing provides a way to follow the call stack to the line number in the method where the exception occurs. The StackTrace property returns the frames of the call stack that originate at the location where the exception was thrown.

How do you throw a custom exception in catch block?

toString() method is used to print out the exception message. We are simply throwing a CustomException using one try-catch block in the main method and observe how the string is passed while creating a custom exception. Inside the catch block, we are printing out the message.


1 Answers

The StackTrace property is virtual - create your own derived Exception class and have the property return whatever you want.

like image 68
James Cadd Avatar answered Sep 23 '22 22:09

James Cadd