异常处理(try catch)

本文详细介绍了Java中异常处理的基本机制,包括try-catch-finally块的使用,主动抛出异常的情况,以及如何自定义异常。通过具体示例展示了如何在方法中捕获并处理异常,以及如何正确地抛出异常。
package day20150904exception;
/**
 * (1)异常处理机制中的try catch
 */
public class ExceptionDemo1 {

    public static void main(String[] args) {
        System.out.println("程序开始");
        try {
            /*
             * 当出现空指针后,jvm创建一个空指针异常实例,
             * 将它抛出来,如果没有try语句,则抛给调用的方法,同时结束程序
             * 
             * 如果有try语句,则跳出try,程序继续往下走
             */
            String str = null;
            System.out.println(str.length());//NullPointerException
            System.out.println(str.charAt(0));

            //空指针异常找到对应参数类型的catch后,把实例传给e
        } catch (NullPointerException e) {
            e.printStackTrace();

            //良好的程序在最后捕捉父类Exception,不可写在最前
        }catch(Exception e){
            e.printStackTrace();

            /**无论try里的代码是否出异常,finally里的代码都要执行
             * 
             * finally里通常不写return
             * 如果写了,try中的return值无法返回方法
             * 而是返回finally中的return值
             */
        }finally{
            System.out.println("finally里的代码都要执行");
        }

//      String str2 = "a";
//      System.out.println(Integer.parseInt(str2));//NumberFormatException

        System.out.println("程序结束");
    }

}
/**
 * 子类重写父类的方法时,子类方法可不抛异常
 * 可抛出父类的部分异常
 * 可抛出父类异常的子类异常
 * 
 * 不可抛出父类没有的异常
 * 不可抛出父类异常的父类异常
*/



package day20150904exception;
//(4)获取异常信息-------------
public class ExceptionDemo4 {
    public static void main(String[] args) {
        //String str = null;
            //抛出NullPointerException
        //System.out.println(str.length());

        try {
            String str ="a";
            //NumberFormatException
            System.out.println(Integer.parseInt(str));
        } catch (NumberFormatException e) {
            e.printStackTrace();

            //获取异常信息:For input string: "a"
            System.out.println(e.getMessage());
        }
        System.out.println("The End");
    }
}
package day20150904exception;
/**
 * 获取错误原因
 * 异常时,为保证异常风格统一
 * 包装之后再抛
 * 想获取真是原因,可调用异常的getCause
 */
public class ExceptionDemo5 {
    public static void main(String[] args) {
        try {
            dosome();
        } catch (Exception e) {
            e.printStackTrace();//爆出异常java.lang.Exception,而不是空指针异常

            //使用getCause方法获取原因
            System.out.println(e.getCause());//运行结果:null
        }
    }

    public static void dosome() throws Exception{
        try {
            String str = null;
            System.out.println(str.length());
        } catch (NullPointerException e) {
            //catch里抛出异常,把NullPointerException包装成Exception抛出
            throw new Exception();
        }
    }
}
package day20150904exception;
//(2)主动抛异常----------
public class Person2 {
    private int age;

    public int getAge() {
        return age;
    }
/**
 * throw异常的2种情况:
 * 1.当前方法中出了个异常
 *   处理当前异常的责任不应该归当前方法管
 *   这时抛出异常,谁调这个方法谁解决
 * 2.当程序遇到一个满足语法要求
 *   但是不符合业务逻辑时
 *   这种情况可以主动throw一个异常出来
 */
    public void setAge(int age) {
        if(age<=0 || age>150){
            throw new RuntimeException("年龄貌似不对哦");
        }
        this.age = age;
    }

    public static void main(String[] args) {
        Person2 p = new Person2();
        p.setAge(1000000);
    }
}
package day20150904exception;
//(3)主动抛异常----------
public class Person3 {
    private int age;

    public int getAge() {
        return age;
    }
/**
 *通常情况下若方法中throw了一个异常实例
 *则必须处理该异常,处理方式有2种:
 *1.为throw异常添加try catch
 *2.在当前方法上声明该类异常的抛出
 *  以便于通知调用者处理该异常
 *  
 *  RuntimeException有点例外(非检查异常)
 */
    //throws表示可能会发生的异常
    public void setAge(int age) throws Exception{
        if(age<=0 || age>150){
            throw new Exception("年龄貌似不对哦");
        }
        this.age = age;
    }
    //永远不要在main方法上写throws
    public static void main(String[] args) {
        Person3 p = new Person3();
        /*
         * 如果自定义异常继承RuntimeException,则可解决可不解决
         * 即try catch可写可不写
         */
        try {
            p.setAge(1000000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package day20150904exception;

import java.io.PrintStream;
import java.io.PrintWriter;



//自定义异常--------------
/**
 * 自定义异常,表示年龄不符人的年龄
 * 
 * 如果继承RuntimeException,则可解决可不解决
 */
//public class MyException extends RuntimeException{
public class MyException5 extends Exception{
    private static final long serialVersionUID = 1L;

    //利用父类的构造方法来建立本类构造方法
    public MyException5() {
        super();
    }

    public MyException5(String arg0, Throwable arg1) {
        super(arg0, arg1);
    }

    public MyException5(String arg0) {
        super(arg0);
    }

    public MyException5(Throwable arg0) {
        super(arg0);
    }


}

-------------------------------------------------
package day20150904exception;
//()抛自定义异常----------
public class Person5 {
    private int age;

    public int getAge() {
        return age;
    }
/**
 *  RuntimeException有点例外(非检查异常)
 */
    public void setAge(int age) throws MyException5{
        if(age<=0 || age>150){
            throw new MyException5("年龄貌似不对哦");//继承Exception
        }
        this.age = age;
    }
    public static void main(String[] args) {
        Person5 p = new Person5();
        /*
         * 如果自定义异常MyException继承RuntimeException,则可解决可不解决
         * 即try catch可写可不写
         */
        try {
            p.setAge(1000000);
        } catch (MyException5 e) {
            e.printStackTrace();
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值