实验6 异常处理
一、实验目的
1、掌握常见异常类的使用环境;
2、掌握异常处理的两种方法;
3、掌握自定义异常类的方法。
二、实验内容
1、在程序中处理常见异常。
2、自定义异常,并在程序中处理异常对象。
三、实验步骤
1、输入三角形三条边长,求三角形面积。
处理可能发生的异常。
class ValueException extends Exception{
public ValueException(){
System.out.println("三角形两边之和必须大于第三边");
}
}
class Triangle{
private double a,b,c;
public Triangle(double a,double b,double c)
{
this.a=a;
this.b=b;
this.c=c;
}
public double area() throws ValueException
{
double p;
double s;
if(a+b<=c||b+c<=a||a+c<=b)
throw new ValueException();
p=(a+b+c)/2;
s=Math.sqrt(p*(p-a)*(p-b)*(p-c));
return s;
}
}
class Test{
public static void main(String[] args)
{
try
{Triangle t=new Triangle(1,4,5);
System.out.println(t.area());
}
catch(ValueException e){
e.printStackTrace();
}
}
}
2、定义Circle类,包含成员变量半径r和计算面积的方法getArea()。
自定义异常类,当半径小于0的时候抛出异常。
class Rexception extends Exception{
Rexception(){
System.out.println("值错误");
}
}
public class Circle {
double r;
final double PI=3.1413;
public Circle(double r) {
this.r=r;
}
public double getArea()throws Rexception {
if(r<=0)
throw new Rexception();
return PI*r*r;
}
public static void main(String[] args) {
try{
Circle c1=new Circle(-4);
System.out.println("圆面积:"+c1.getArea());
}catch(Rexception e){
System.out.println("半径不能小于等于0");
}
}
}。