不能抛出RuntimeException类型的异常

顽劣的石头 2012-10-16 12:17:35
public class RuntimeException {

private static void throwit() throws Exception
{
System.out.print("throwit ");
//throw new Exception();
throw new RuntimeException(); /* eclipse中提示这句代码有误,给出的错误提示是“No exception of type RuntimeException can be thrown; an exception type must be a subclass of Throwable” */
}

public static void main(String[] args) {

try
{
System.out.print("try ");
throwit();
}
catch(Exception e)
{
System.out.print("catch ");
}
finally
{
System.out.print("finally ");
}
System.out.println("last");
}
}

上述程序中,代码 throw new RuntimeException(); 在 eclipse中提示这句代码有误,给出的错误提示是“No exception of type RuntimeException can be thrown; an exception type must be a subclass of Throwable”
网上查看到可以抛出RuntimeException类型的异常,到我这怎么就出错了,求高手解答,谢谢!
...全文
502 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
顽劣的石头 2012-10-16
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

方法声明中throws出的是checked exception。

RuntimeException及其子类是non-checked exception。

private static void throwit() throws Exception
=>
private static void throwit()
去掉这个
[/Quote]
我试过了,这个去不去掉都没影响的,谢谢。
顽劣的石头 2012-10-16
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

LZ啊,你自己的类名就叫RuntimeException,你这个类又不是Throwable的子类,怎么作为异常抛出

你要不肯改名,就试试这样:
new java.lang.RuntimeException()
[/Quote]
问题确实出在这里,没注意到这个问题,谢谢。
龙四 2012-10-16
  • 打赏
  • 举报
回复
LZ啊,你自己的类名就叫RuntimeException,你这个类又不是Throwable的子类,怎么作为异常抛出

你要不肯改名,就试试这样:
new java.lang.RuntimeException()
huntor 2012-10-16
  • 打赏
  • 举报
回复
方法声明中throws出的是checked exception。

RuntimeException及其子类是non-checked exception。

private static void throwit() throws Exception
=>
private static void throwit()
去掉这个

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧