java异常处理练习(1)

java异常处理练习(1)

练习1:

public class Train1 {
    public static void main(String[] args) {
        try {
//            传递一个字符串参数给Exception 的构造器
            throw new Exception("自定义的异常!");
        } catch (Exception e) {
//            在 catch 子句里捕获此异常对象,并且打印字符串参数
            System.err.println(e.getMessage());
            e.printStackTrace();
        } finally {
//            添加一个finally 子句,打印一条信息以证明这里确实得到了执行
            System.err.println("这里执行了!");
        }
    }
}

练习2:

public class Train2 {
    public static void main(String[] args) {
        //定义一个对象引用并初始化为null
        StringBuffer sb=null;
        try {
//            尝试用此引用调用方法
            sb.equals("test");
        } catch (Exception e) {
            //捕获异常
            e.printStackTrace();
        }

        System.out.println(sb);
    }
}

 

练习3:

public class Train3 {
    public static void main(String[] args) {
        //声明数组大小
        String[] a= new String[3];
        try {
            a = new String[]{"零","壹","贰"};
            //数组越界
            a[3]="肆";
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

练习4

//自定义的异常

public class CustomizeException extends Exception {
    private String st;
    CustomizeException(String st){
        super();
        this.st = st;
    }
    public void function(){
        System.out.println("Exception:"+st);
    }
}
public class Train4 {
    public static void main(String[] args) {
        try {
            throw new CustomizeException("自定义的异常");
        } catch (CustomizeException e) {
            e.function();
            e.printStackTrace();
        }
    }
}

 

 

转载于:https://my.oschina.net/u/2551519/blog/706285