Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Exception throw object and get object from catch

Tags:

java

I want to pass object while getting exception and getting from catch. I have UserDataException extend from Exception

throw new UserDataException("Media uploaded failed",mediaDO, dupkExp);

mediaDO is object.

if possible to get this mediaDo object from catch statement

catch (UserDataException uExp) {

    }

UserdataException calss :

public class UserDataException extends Exception {

private static final String ERROR = "Database Transaction Error: ";
private static final String DKERROR = "Duplicate Key Error";

/**
 * 
 */
private static final long serialVersionUID = 6209976874559850953L;

/**
 * 
 */
public UserDataException(String message, Throwable throwable) {
    super(message, throwable);
}

public UserDataException(String message) {
    super(message);
}

/**
 * <code>UserDataException</code> thrown with message and throwable object
 * 
 * @param schdulerData
 * @param message
 * @param throwable
 */
public UserDataException(String message, SchedulerData schdulerData, final Throwable throwable) {

    super(ERROR + message, throwable);
}

/**
 * <code>UserDataException</code> thrown with message and throwable object
 * 
 * @param schdulerData
 * @param message
 * @param throwable
 */
public UserDataException(String message, MediaDO mediaDO, final Throwable throwable) {

    super(DKERROR + message, throwable);
}

}

Please help if possible..

like image 985
nmkkannan Avatar asked Dec 11 '22 23:12

nmkkannan


1 Answers

You have to store a reference to that object in your exception class and use a getter to get it :

private MediaDO mediaDO;

public UserDataException(String message, MediaDO mediaDO, final Throwable throwable) {
    super(DKERROR + message, throwable);
    this.mediaDO = mediaDO;
}

public MediaDO getMediaDO()
{
    return mediaDO;
}

Then in the catch block :

catch (UserDataException uExp) {
    MediaDO mediaDO = uExp.getMediaDO();
    ...
}
like image 99
Eran Avatar answered Dec 28 '22 07:12

Eran