版权声明:Genius https://blog.csdn.net/weixin_41987706/article/details/91432722
夜光序言:
如果爱太荒凉 我陪你梦一场
赎回你所有泪光
这一路有多远 这三世有多长
执手到地老天荒
正文:Java的异常处理机制
用户自定义异常类示例
异常的处理
/* 定义一个输入图形边长为负数的异常处理类SizeException
和三条边长无法组成三角形的异常处理类IllegalSizeException.java */
package common; //将异常保存在包common里
public class SizeException extends Exception
{
String s;
public SizeException()
{
s="所输数值不能为负数!";
}
public String toString() //输出出错信息
{
return s;
}
}
package common; //将异常保存在包common里
public class IllegalSizeException extends Exception
{
String s;
public IllegalSizeException()
{
s="三角形的3条边长度不合理,请重新输入!";
}
public String toString() //输出出错信息
{
return s;
}
}
/* 编写一个测试类 TestTriangleLast.java, 测试三角形类运行是否正确 */
import shapes.*;
import common.*;
public class TestTriangleLast
{
public static void main(String args[])
{
TriangleLast t; //声明一个三角形对象
try {
t= new TriangleLast(80,100,50); //(1)测试给定3条边长的三角形
// t= new TriangleLast(80,-100,50); //(2)测试负数异常 SizeException
// t= new TriangleLast(80,10,50); //(3)测试 IllegalSizeException
t.setCircumference();
t.setArea();
System.out.println("\n三角形: TriangleLast(80,100,50),周长="
+t.getCircumference()+" 面积="+t.getArea()+"\n");
}
catch(SizeException e1) { //捕获异常1:边长为负数
System.out.println(e1.toString()+"\n ");
}
catch(IllegalSizeException e2){ //捕获异常2:3条边长不合理
System.out.println(e2.toString()+"\n ");
}
}
}
//增加了异常处理的三角形类
package shapes;
import java.awt.*;
import common.*; //加载common包中的异常类
public class TriangleLast extends TriangleNew
{
public TriangleLast(int a,int b,int c) throws SizeException, IllegalSizeException
{
super(a,b,c); //调用父类的构造方法
if(sidea<0|sideb<0|sidec<0)
throw (new SizeException()); //当边值为负时抛出异常
if((sidea+sideb)<sidec|(sidea+sidec)<sideb|(sidec+sideb)<sidea)
throw (new IllegalSizeException()); //当三条边长度不合理抛出异常
}
}
//方式1
public class TestSystemException
{
public static void main(String[] args)
{
int a=0,b=5;
try //try块启动异常处理机制
{
System.out.println(b/a); //以零为除数,引发系统定义的算术异常
}
catch(Exception e) //catch块捕获异常
{
System.out.println(e.toString()); //输出异常的具体信息
}
System.out.println(b+a); //增加了异常捕获处理后,此行代码可正常执行
}
}
//方式2
public class TestSystemException1
{
public static void main(String args[])
{
int a=0,b=5;
System.out.println(b/a); //以零为除数,引发系统定义的算术异常
System.out.println("a+b="+a+b); //出现异常后,正常语句不能被执行
}
}