如何创建一个可以使用try.....catch.......捕获的异常
代码很简单,大家一看基本上就能明白(有一定的java基础,熟悉try......catch.....finally的使用方法)
1 package com.nokia.test1; 2 3 4 public class test { 5 6 7 public static void main(String[] args) { 8 9 NumberTest n = new NumberTest(); 10 11 //捕获异常 12 try{ 13 System.out.println("商="+n.div(1,0)); 14 15 }catch(customException1 yc){ 16 System.out.println(yc.getMessage()); 17 yc.printStackTrace(); 18 } 19 catch(customException2 yx) 20 { 21 System.out.println(yx.getMessage()); 22 yx.printStackTrace(); 23 } 24 catch(Exception y) 25 { 26 System.out.println(y.getMessage()); 27 y.printStackTrace(); 28 } 29 30 finally{ System.out.println("finally!");} ////finally不管发没发生异常都会被执行 31 32 33 34 } 35 36 } 37 38 class customException1 extends Exception{ 39 40 public customException1(String msg) { 41 super(msg); 42 // TODO Auto-generated constructor stub 43 } 44 } 45 46 47 class customException2 extends Exception{ 48 49 public customException2(String message) { 50 super(message); 51 // TODO Auto-generated constructor stub 52 } 53 } 54 55 56 class NumberTest{ 57 58 public int div(int x, int y) throws customException1, customException2 { 59 60 if (y<0) { 61 62 throw new customException1("您输入的是"+y+",规定除数不能为负数!"); //抛出异常 63 } 64 65 if(y==0) 66 { 67 throw new customException2("您输入的是"+y+",除数不能为0!"); 68 } 69 70 return x / y; 71 } 72 73 74 }
如有什么好的建议,请畅所欲言!!!!!
参考链接:http://blog.csdn.net/stellaah/article/details/6738424