I have a small piece of code that runs through some transactions for processing. Each transaction is marked with a transaction number, which is generated by an outside program and is not necessarily sequenced. When I catch an Exception in the processing code I am throwing it up to the main class and logging it for review later. I'd like to add the transaction number to this thrown Exception. Is it possible to do this while still maintaining the correct stack trace?
For Example:
public static void main(String[] args) { try{ processMessage(); }catch(Exception E){ E.printStackTrace(); } } private static void processMessage() throws Exception{ String transNbr = ""; try{ transNbr = "2345"; throw new Exception(); }catch(Exception E){ if(!transNbr.equals("")){ //stack trace originates from here, not from actual exception throw new Exception("transction: " + transNbr); }else{ //stack trace gets passed correctly but no custom message available throw E; } } }
In order to create custom exception, we need to extend Exception class that belongs to java.lang package. Consider the following example, where we create a custom exception named WrongFileNameException: public class WrongFileNameException extends Exception { public WrongFileNameException(String errorMessage) {
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.
Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the 'throw' keyword.
Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.
Try:
throw new Exception("transction: " + transNbr, E);
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr at ... at ... caused by OriginalException ... at ... at ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With