一、阅读下面程序,理解异常处理机制,写出运行结果。
class MyExp extends Exception{
MyExp(){
super("自定义异常");
}
}
public class Exp2 {
public void f1(int n) {
System.out.println("f1前面");
f2(n);
System.out.println("f1后面");
}
public void f2(int n) {
System.out.println("f2前面");
try{
System.out.println("try的前面");
f3(n);
System.out.println("try的后面"); //发生异常时不会输出}catch(MyExp e){
System.err.println(e.getMessage());
}finally{
System.out.println("无论是否发生异常");
}
System.out.println("f2后面");
}
public void f3(int n) throws MyExp{
System.out.println("f3前面");
f4(n);
System.out.println("f3后面"); //发生异常时不会输出}
public void f4(int n) throws MyExp{
System.out.println("f4前面");
if(n<0){
throw new MyExp();
}
System.out.println(n); //发生异常时不会输出
System.out.println("f4后面"); //发生异常时不会输出}
public static void main(String[] args) {
Exp2 exp = new Exp2();
exp.f1(-4);
}
}
二、按模板要求,将[代码]处替换为Java程序代码。
import java.util.*;
class MyException extends [代码]{//自定义异常
String message;
MyException(int age){
message=age+"年龄异常";
}
public String getMessage(){
return message;
}
}
class People{
private int age;
int getAge(){
return age;
}
void setAge(int age) [代码]{
if(age>160||age<0){
[代码] //抛出异常
}
this.age=age;//赋值
}
}
class TW{
public static void main(String args[]){
Scanner reader=new Scanner(System.in);
System.out.printf("输入年龄:");
int x=[代码];//键盘输入
People a=new People();
[代码] //设置对象a的属性age,需要捕捉异常并处理。
System.out.println(a.getAge());
}
}
三、编程:自定义异常类NotSanjiaoException,可以参照前面二个作业自行设计。
自定义三角形类Sanj,其中有成员x,y,z,作为三边长,构造方法Sanj(a,b,c)分别给x,y,z 赋值,方法求面积getArea和显示三角形信息(三个边长)showInfo,这2个方法中当三条边不能构成一个三角形时要抛出自定义异常NotSanjiaoException,否则显示正确信息。在另外一个类SanjTest中的主方法中构造一个Sanj对象(三边为命令行参数输入的三个整数),显示三角形信息和面积,要求捕获异常。