代码实例:
public class Try_catch { public static void main(String[] args){ Scanner input=new Scanner(System.in); try{ System.out.println("请输入第一个数:"); int one=input.nextInt(); System.out.println("请输入第二个数:"); int two=input.nextInt(); System.out.println("两数相除得:"+one/two); }catch(InputMismatchException e){ e.printStackTrace(); System.out.println("请输入数字!!!"); }catch(ArithmeticException e){ System.out.println("除数不能为零!!!"); e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); System.out.println("未知的异常!!!"); }finally{ System.out.println("finally语句块用来善后,比如出现异常后关闭一些文件等"); } System.out.println("程序结束!"); } }注意:自定义异常类必须继承于与之相近的异常类或是Exception 【由于有了含参的构造器,编译器便不会再给分匹配无参构造器,而有时候需要使用,所以可以再添加一个无参的构造器】
public class Custom_Exception extends Exception{ public Custom_Exception(){ } public Custom_Exception(String message){//含参的构造器 super(message); } }initCause()方法对异常进行包装的,目的为了出了问题的时候能够追根究底。因为一个项目,越往底层,可能抛出的异常类型会用很多,如果你在上层想要处理这些异常,你就需要挨个的写很多catch语句块来捕捉异常,这样是很麻烦的。如果我们对底层抛出的异常捕获后,抛出一个新的统一的异常,会避免这个问题。
public class Exception_link { public static void main(String[] args) { Exception_link cs=new Exception_link(); try{ cs.test2(); }catch(Exception e){ e.printStackTrace(); } } public void test1() throws Custom_Exception{ //调用自定义的异常类 throw new Custom_Exception("喝酒别开车!"); } public void test2(){ try{ test1(); }catch(Custom_Exception e){ //构造RuntimeException RuntimeException newExc=new RuntimeException("司机一滴酒,亲人两行泪"); newExc.initCause(e); //将原异常包装,抛出运行时异常 throw newExc; } } }