Java异常抛出对象并从catch获取对象

时间:2015-05-14 08:46:58

标签: java

我想在获取异常并从catch获取时传递对象。 我从{Exception

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

mediaDO是对象。

如果可能,从mediaDo语句

获取此catch对象
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);
}

}

请尽可能帮助..

1 个答案:

答案 0 :(得分:8)

您必须在异常类中存储对该对象的引用,并使用getter来获取它:

private MediaDO mediaDO;

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

public MediaDO getMediaDO()
{
    return mediaDO;
}

然后在catch区块中:

catch (UserDataException uExp) {
    MediaDO mediaDO = uExp.getMediaDO();
    ...
}