java中处理异常需要注意的事项

    技术2022-05-11  67

    1.throws的应用: 1).定义方法时,以后调用此方法,需要进行try-catch语句处理. 2).如果对语句不希望处理try-catch语句,以用throw进行抛出. 2.异常的处理结构: try-catch-finally 3.自定义异常类 必须继承Exception 4.在自定义位置需要写明:throws Exception catch语句为if-else结构.只匹配第一个.所以放置顺序很重要. finnally,不管try是否发生作用,它均会执行.即使在之前遇到return语句. 如果希望它不执行,需要遇到system.exit(0)语句. 5. 例如 try {if(x<0)throw new Xxxexception("xxx");else throw new Yyyexception("yyy");} catch (Xxxexception e) {..} catch (Yyyexception e) {...} 6.在类的继承时,子类throw的异常必须事父类异常的子异常,不能throw新的异常.只能比父类的少,不能比父类的多. 附例:自定义异常.   class  Test {    public int divide(int x,int y) throws myException,Exception    {        if(y<0)              throw new myException("y is minus"+y);        int result;        result=x/y;        return result;    }}      class  myException  extends  Exception {    public myException (String msg)    {        super(msg);    }} public   class  ByZero {     public static void main(String[] args)     {        try        {            new Test().divide(3,-9);        }       catch(myException e)       {           System.out.println(e.getMessage());  //返回字符串           e.printStackTrace(); //返回详细信息      }       catch(Exception e)       {             System.out.println(e.getMessage());       }           System.out.println("he");       }}          

    最新回复(0)