package Domain;
public class ExceptionTest {
public static void main(String[] args)throws Exception {
int[]arr = new int[10];
try{
int a = arr[10];
System.out.println(a);
}catch(ArrayIndexOutOfBoundsException ex){
throw new Exception("数组越界",ex);
}finally{
System.out.println("验证Finally的运行");
}
}
}
package Danger;
public class DangerException extends Exception{
String imformation;
DangerException(String imformation){
this.imformation=imformation;
}
void toShow(){
System.out.println(imformation);
}
}
package Danger;
public class Machine {
String name;
Goods g;
public boolean isDanger(String name) {
String score[] = {"炸弹","毒药","刀具","枪支"};
boolean flag =false;
for(int i=0;i<score.length;i++) {
if(name.equals(score[i])) {
flag = true;
break;
}
}
return flag;
}
void checkBag(Goods g){
this.g=g;
name=g.getName();
try{
if(isDanger(name)){
System.out.print(name);
throw new DangerException("是危险品!!!"+"\n");
}
else{
System.out.print(name);
throw new DangerException("不是危险品!"+"\n");
}
}catch(DangerException e){
e.toShow();
}
}
}
package Danger;
public class Goods{
String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
package Danger;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
while(true) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入物品:");
String input=sc.nextLine();
Goods g=new Goods();
g.setName(input);
Machine m=new Machine();
m.checkBag(g);
}
}
}
原文:https://www.cnblogs.com/buxiu888/p/11701136.html