0

The exception is never shown . extended Exception class and override the method toString.and then called it.according to the condition it should display hahah , but it doesn't show anything..no errors either.

class Excp extends Exception {

        public String toString() {
            return "hahah";

        }
    }

    public class exc {

        boolean a = false;

        void hey() throws Excp {

            if (a)
                throw new Excp();

        }

        public static void main(String... s) {

            try {
                new exc().hey();
            } catch (Excp e) {
                System.out.println(e);
            }

        }
    }
4

3 回答 3

2

这里

{
    if(a)
    throw new Excp();
}

一个是false。永远不要进入条件,因为您在初始化对象时没有使真。

尝试

try
    {   
        Excp exc = new Excp();
        exc.a= true;
        exc.hey();
    }

旁注:

1)请遵循命名约定。

2)提供封装。

3)始终格式化您的代码。

于 2013-10-02T04:54:40.777 回答
2

你的情况

if(a)

将在您初始化时返回 false a=false。因此该if块不会执行该语句

throw new Excp();
于 2013-10-02T04:54:49.803 回答
1

我认为您希望有一个带有您自己的错误消息的自定义异常,如果是这样,您可以这样做

class MyException extends Exception{
    MyException(String errorMsg){
         super(errorMsg);
    }
}

class Test{
    public static void main(String[] args){
          if(someCondition)
               throw new MyException("My error message");
    }
}
于 2013-10-02T04:59:46.177 回答