[java] Add custom message to thrown exception while maintaining stack trace in Java

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;
        }
    }
}

This question is related to java exception exception-handling

The answer is


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 ...

You can use your exception message by:-

 public class MyNullPointException extends NullPointerException {

        private ExceptionCodes exceptionCodesCode;

        public MyNullPointException(ExceptionCodes code) {
            this.exceptionCodesCode=code;
        }
        @Override
        public String getMessage() {
            return exceptionCodesCode.getCode();
        }


   public class enum ExceptionCodes {
    COULD_NOT_SAVE_RECORD ("cityId:001(could.not.save.record)"),
    NULL_POINT_EXCEPTION_RECORD ("cityId:002(null.point.exception.record)"),
    COULD_NOT_DELETE_RECORD ("cityId:003(could.not.delete.record)");

    private String code;

    private ExceptionCodes(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }
}

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source


Following code is a simple example that worked for me.Let me call the function main as parent function and divide as child function.
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first.

class Main {
    public static void main(String args[]) {
        try{
            long ans=divide(0);
            System.out.println("answer="+ans);
        }
        catch(Exception e){
            System.out.println("got exception:"+e.getMessage());

        }

    }
    public static long divide(int num) throws Exception{
        long x=-1;
        try {
            x=5/num;
        }
        catch (Exception e){
            throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
        }
        return x;
    }
}  

the last line return x will not run if error occurs somewhere in between.


There is an Exception constructor that takes also the cause argument: Exception(String message, Throwable t).

You can use it to propagate the stacktrace:

try{
    //...
}catch(Exception E){
    if(!transNbr.equals("")){
        throw new Exception("transaction: " + transNbr, E); 
    }
    //...
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to exception

Connection Java-MySql : Public Key Retrieval is not allowed How to print an exception in Python 3? ASP.NET Core Web API exception handling Catching FULL exception message How to get exception message in Python properly What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean? Argument Exception "Item with Same Key has already been added" The given key was not present in the dictionary. Which key? sql try/catch rollback/commit - preventing erroneous commit after rollback

Examples related to exception-handling

Catching FULL exception message Spring Resttemplate exception handling How to get exception message in Python properly Spring Boot REST service exception handling java.net.BindException: Address already in use: JVM_Bind <null>:80 Python FileNotFound The process cannot access the file because it is being used by another process (File is created but contains nothing) Java 8: Lambda-Streams, Filter by Method with Exception Laravel view not found exception How to efficiently use try...catch blocks in PHP