throwable不会编译

时间:2013-03-05 20:45:11

标签: java

首先,我必须说我读了以下内容:http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

我尝试编译时遇到的错误如下:

TestException.java:14: error: incompatible types

static void doRisky(String test) throws ScaryException
                                                ^
required: Throwable
found:    ScaryException

TestException.java:19: error: incompatible types
                        throw new ScaryException();
                                      ^
required: Throwable
found:    ScaryException

TestException.java:34: error: incompatible types
                catch ( ScaryException  se)
                        ^
  required: Throwable
  found:    ScaryException

3 errors

我假设错误消息给了我某种类型的提示,但我只是看不出它是什么。

import java.lang.*;
/** add this as to get it to compile */
class ScaryException extends Exception
{
/** how come I can't put code here? */
}

public class  TestException {

    static void doRisky(String test) throws ScaryException{
        System.out.println ("start risky");    
        if ("yes".equals(test)) {
            throw new ScaryException();
        }
        System.out.println("end risky");
    }

    public static void main(String [] args){
        String test = "no";
        try{
            System.out.println("start try");
            doRisky(test);
            doRisky("yes");
            System.out.println("end try");
        }
        catch ( ScaryException  se){
            System.out.println("Got What " + se);
        }
        finally{
            System. out. println( "finally") ;
        }

        System.out.println("end of main");
    }
}

2 个答案:

答案 0 :(得分:2)

Java异常必须扩展Throwable(通过扩展Exception或其中一个子类直接扩展,或者最好间接扩展ScaryException。显然你的{{1}}课没有。

答案 1 :(得分:1)

为了编译,ScaryException必须是扩展Throwable或其子类之一的类。 ScaryException根本不存在,或者它不会延伸任何Throwable个孩子。

相关问题