【java】异常处理

来源:互联网 发布:131458淘宝信誉查询网 编辑:程序博客网 时间:2024/06/06 09:41

java中已经帮我们写好了异常类。在运行中出现异常会立刻中断程序并抛出异常信息。那么如果我们当异常出现时我们仍然想继续完成程序的运行,那么就需要做异常处理。形如:

try{    做某件操作;}catch(Exception e){    捕捉到异常;}finally{    无论有没有异常我都会到这里来;}

另有关键字throw和throws。

throw可以使得程序直接抛出异常:

try{    throw new Exception(“自己抛出的异常”);}catchException e){    System.out.println(e);}运行结果:java.lang.Exception:自己抛出的异常

throws是指如果当前方法出现了异常,我不会进行处理,也不会终止程序的运行。但要在该方法被调用的地方进行异常处理,比如:

class Math{    public int div(int a,int b) throws{        int temp = a/b;        return temp;    }   }public class ThrowsLearn{    public staic void main(String args[]){        Math math = new Math();        try{            math.div(10,0);         }catch(Exception e){            System.out.println(e);        }    }}
0 0