1 /* 2 try - catch语句的例子,模拟向货船上装载集装箱 3 ,若是货船超重,那么货船认为这是一个异常,将拒绝装载集装箱, 4 但不管是否发生异常,货船都须要正点起航。 5 */ 6 package st; 7 class DangerException extends Exception 8 { 9 final String message ="超重"; 10 public String warnMess(){ 11 return message; 12 } 13 } 14 class CargoBoat 15 { 16 int realContent; //实际装载的重量 17 int maxContent; //最大装载量 18 public void setmaxContent(int c) { 19 maxContent=c; 20 } 21 public void judgeload(int load ) throws DangerException 22 { 23 if(realContent +load<maxContent) 24 realContent +=load; 25 else 26 throw new DangerException(); 27 System.out.println("目前装载了"+realContent+"吨货物"); 28 } 29 } 30 public class example_1 31 { 32 public static void main(String args[]) 33 { 34 CargoBoat ship = new CargoBoat(); 35 ship.setmaxContent(1000); 36 int [] m={600,400,367,555}; 37 try 38 { 39 for(int i=0 ; i<4 ; i++) 40 ship.judgeload(m[i]); 41 } 42 catch(DangerException e) 43 { 44 System.out.println(e.warnMess()); 45 System.out.println("没法再装载重量是"+m+"吨的集装箱"); 46 } 47 finally 48 { 49 System.out.println("货船将正点起航"); 50 } 51 52 } 53 }
/* 目前装载了600吨货物 超重 没法再装载重量是[I@c9d92c吨的集装箱 货船将正点起航 */