throw Exception 的简单问题

male110 2007-04-09 08:46:26
class Test{
public void throwException(){
throw new Exception("aaa");
}
}
Main.java:18: 未报告的异常 java.lang.Exception;必须对其进行捕捉或声明以便抛出

怎么样才能抛出去呢?
try
{
throw new Exception("aaa");
}catch(Exception e)
{
throw e;
}
也不行!
...全文
303 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
程序员的救赎 2011-06-22
  • 打赏
  • 举报
回复
我也学到了
male110 2007-04-09
  • 打赏
  • 举报
回复
谢谢,分数平分!
yiyi2007 2007-04-09
  • 打赏
  • 举报
回复
以上代码均成运行成功(本人运行过了)。这是老师给的代码。
代码实现的是输入两个数,后相除,输出结果。

代码中有throws,有多重嵌套,有自定义异常等常用的异常格式。

初学者可以好好看一看
yiyi2007 2007-04-09
  • 打赏
  • 举报
回复
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;


public class Tester {

/**
* @param args
*/
public static void main(String[] args) {
int a,b;
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));

try {
System.out.print("a:");
a=Integer.parseInt(reader.readLine());
System.out.print("b:");
b=Integer.parseInt(reader.readLine());
System.out.println("result="+ new Divider().perform(a, b));
} catch (NumberFormatException e) {
System.out.println("NumberFormatException found, msg:"+e.getMessage());
} catch (IOException e) {
System.out.println("IOException found, msg:"+e.getMessage());
} catch (MyException e) {
System.out.println("MyException found, msg:"+e.getMessage());
} catch(ArithmeticException e){
System.out.println("ArithmeticException found, msg:"+e.getMessage());
}

System.out.println("process end..");


}

}


class Divider {
Float perform(int a, int b) throws ArithmeticException,MyException{
Float result=null;
if(a==12)
throw new MyException("12 is not a right number!");
result=(float)(a/b);
return result;
}
}

public class MyException extends Exception {

public MyException(String message)
{
super(message);
}

}


关于异常的常用几种写法。
伟大的左前卫 2007-04-09
  • 打赏
  • 举报
回复
class Test{
public void throwException()throws Exception{
throw new Exception("aaa");
}
}

62,634

社区成员

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

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