自定义异常问题

时间:2014-05-19 09:15:14

标签: java exception-handling

我通过创建具有相同名称的xyException文件创建了自定义异常.java。我在用户违反条件时显示此异常。这在我的本地机器上运行得非常好。但是,当我将代码放在服务器上时,我得到以下错误:

Exception in thread "main" java.lang.NoClassDefFoundError: xyException
at A.<init>(A.java:24)
at mainClass.<init>(mainClass.java:27)
at mainClass.main(mainClass.java:251)

有趣的是,上述所有错误都出现在我调用其他类的默认构造函数的行上。

line:24:object_B = new B();
line:27:mainClass A list = new A();
line:251:mainClass mainClass M = new mainClass();

在添加此异常之前,代码工作正常。

public class xyException extends Exception
{
    public stonesRemoveException(String msg)
    {
       super(msg);
    }
}
void someFunc()(//parameters) 
{
    //code
    try
    {
       if(//condition)
       {
           throw new xyException("error" + some_variable + "string");
       }
       else if(//condition)
       {
           throw new xyException("error" + some_variable + "string");
       }
     }
     catch(xyException e)
     {
        String error = e.getMessage();
        System.out.println(error);
        someFunc(//parameters) 
     }

 }

但是,我不知道我哪里错了?

2 个答案:

答案 0 :(得分:1)

创建您的异常类,如:

public class xyException extends Exception {

    public xyException(String msg) {
        super(msg);
    }

}

在业务逻辑中使用以下条件来引发用户定义的异常,而不是在用户定义的类中。

if(x>y)
{
    //code
}
else if //condition
{
    //code
}
else
    //code

这是因为您必须致电super(msg);Constructor call must be the first statement in a constructor

因此,如果您尝试通过删除if来添加super(msg)条件,则无法在if调用之前添加super();条件,那么您的课程将不再是{{1} } class

答案 1 :(得分:0)

确保您的异常类已集成到您在服务器上部署的文件中。