异常处理
1.计算两数相乘的结果,要求乘数不能超过99,超过就抛出异常
class MyException extends Exception{
//自定义异常类,继承Exception类
public MyException(String msg){
//构造方法接收异常信息
super(msg); //调用父类中的构造方法
}
}
public class Throwdemo {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
System.out.print("请输入一个整数:");
int a = scan.nextInt();
System.out.print("请输入另外一个整数:");
int b = scan.nextInt();
int sum = a * b;
if( sum>99){
try{
throw new MyException("超出范围了!");
}catch(Exception e){
System.out.println(e);
}
}
else
System.out.print("他们的乘是" + sum);}}
2.车站检查危险品的设备,如果发现危险品会发出警告。编程模拟设备发现危险品。
1.编写一个一个Exception的子类DangerException,
该子类可以创建异常对象,该异常对象调用toShow()方法输出:“属于危险品”。
2.编写一个Machine类,
该类的方法checkBag(Goods goods)当发现参数goods是危险品时(goods的isDanger属性是true)将抛出DangerException异常。
3.程序在主类的main方法中的try~catch语句的try部分让Machine类的实例调用checkBag(Goods goods)方法,
如果发现危险品就在try~catch语句的catch部分处理危险品。
public class Goods {
boolean isDanger;
String name;
public void setIsDanger(boolean boo) {
isDanger = boo;
}
public boolean isDanger() {
return isDanger;
}
public void setName(String s) {
name = s;
}
public String getName() {
return name;}}
public class DangerException extends Exception {
String message;
public DangerException() {
message = "危险品!";
}
public void toShow() {
System.out.print(message+" ");}}
public class Machine {
public void checkBag(Goods goods) throws DangerException {
if(goods.isDanger()) {
DangerException danger=new DangerException();
throw danger; //抛出danger
}
else {
System.out.print(goods.getName()+"不是危险品! ");}}}
public class Check {
public static void main(String args[]) {
Machine machine = new Machine();
String name[] ={
"苹果","炸药","西服","硫酸","手表","硫磺"};
Goods [] goods = new Goods[name.length]; //检查6件货物
for(int i= 0;i<name.length;i++) {
goods[i] = new Goods();
if(i%2==0) {
goods[i].setIsDanger(false);
goods[i].setName(name[i]);
}
else {
goods[i].setIsDanger(true);
goods[i].setName(name[i]);
}
}
for(int i= 0;i<goods.length;i++) {
try {
machine.checkBag(goods[i]);
System.out.println(goods[i].getName()+"检查通过");
}
catch(DangerException e) {