【问题标题】:throwable will not compilethrowable 不会编译
【发布时间】:2013-03-05 20:45:10
【问题描述】:

首先我必须说我阅读了以下内容: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");
    }
}

【问题讨论】:

  • 您的ScaryException 是否扩展了 throwable 的子类?通常是java.lang.Exception?

标签: java


【解决方案1】:

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

【讨论】:

  • 最简单的方法是将“扩展异常”添加到ScaryException 的定义中,例如class ScaryException extends Exception。当然,假设您还没有做过一些古怪的事情,比如重新发明异常处理。 :)
【解决方案2】:

要编译,ScaryException 必须是扩展 Throwable 或其子类之一的类。 ScaryException 根本不存在,或者它没有扩展任何Throwable 的孩子。

【讨论】:

    猜你喜欢
    • 2021-10-05
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2013-08-02
    • 2018-10-23
    • 2015-09-22
    • 2017-12-22
    相关资源
    最近更新 更多