一、捕获异常
try{...}catch{...}:将可能发生异常的代码放在try{...}中。
public class Hi {public static void main(String[] args){// var a = 1/0;try {var a = 1/0;} catch (Exception e) {System.out.println(e);//TODO: handle exception}}}
二、抛出异常
2.1 系统自动抛出
// 例子var a = 1/0;
2.2 throw
// 例子if(true){throw new NumberFormatException();}
2.3 throws(用在方法上,表示可能有的异常,抛出后交由上层方法捕获处理)
public class Hi {public static void main(String[] args){// var a = 1/0;try {// var a = 1/0;dev(1,0);} catch (Exception e) {System.out.println(e);//TODO: handle exception}}static int dev(int a,int b) throws Exception{return a/b;}}
