第十章、异常
一、异常抛出:
Throw new Typeexception(“ ”) //带参数异常
- 所有的标准异常类都有两个构造器:
- 默认构造器,接受参数字符串作为参数。
二、捕获异常:
1、Try块:
try{ //若在方法内部抛出了异常,这个方法将在抛出异常的过程中结束,要不希望此方法结束, //可以使用try块进行尝试 }
2、异常处理程序:
try{ }catch(Type1 id1){ //对抛出的异常进行处理 }
注:异常处理程序必须紧跟在try块之后,当异常抛出时,catch负责处理异常。
三、创建自定义异常:
1、要定义自己的异常,必须继承已有的异常,代码如下:
package com.exception; class Myexception extends Exception{ public Myexception(){ } public Myexception(String s){ super(s); } } public class Fullconstructors { public static void f() throws Myexception{ System.out.println("f()"); throw new Myexception(); } public static void g() throws Myexception{ System.out.println("g()"); throw new Myexception("origining in g()"); } public static void main(String[] args) { // TODO Auto-generated method stub try{ f(); }catch(Myexception e){ e.printStackTrace(System.out);//printStackTrace将打印从方法调用处直到异常抛出处的方法调用序列,信息被送到Sysem.out } try{ g(); }catch(Myexception e){ e.printStackTrace();//信息被送到标准错误流 } } }
2、异常与记录日志:
四、异常的说明:
Void f() throws Exception //使用throws进行异常说明,紧跟在形式参数之后。
五、捕获所有的异常:
用Exception e这个基类来捕获所有异常,放在异常捕获的最后面。
六、使用finally:
无论异常是否会抛出,finally子句总会执行。