《Java基础入门 极速版》

ch06 异常


【例题1】 编译错误、运行错误、运行异常举例

package cn.du.ch06;

public class Java01_Exception {
    public static void main(String[] args) {

        // TODO 错误
        // 1. 类型转换错误  编译错误 爆红
        String s = "123";
        Integer i = (Integer)s;
        Integer j = Integer.parseInt(s);

        // 2. java.lang.StackOverflowError
        //    递归
        // Error : 错误
        System.out.println("运行错误 Error【杜老师整理】");
        test();

        // 3. java.lang.NullPointerException
        // 异常 : Exception
        // TODO 异常的分类
        // 3.1 可以通过代码恢复正常逻辑的异常,称之为运行期异常。(RuntimeException)
        // 3.2 不可以通过代码恢复正常逻辑的异常,称之为编译期期异常(Exception)
        System.out.println("异常 Exception【杜老师整理】");
        User user = null;
        System.out.println(user.toString());
    }
    public static void test() {
        test();
    }
}
class User {

}
图1 编译错误
图2 运行错误
图3 异常

异常处理语法:

//TODO try :尝试
//TODO catch :  捕捉
//捕捉多个异常的时候,需要先捕捉范围小的异常,然后再捕捉范围大的异常
// TODO finally : 最终

try {
    //可能会出现异常的代码
    //如果出现异常,那么JVM会将异常进行封装,形成一个具体的异常类,然后将这个异常抛出
    //所有的异常对象都可以被抛出
} catch ( 抛出的异常对象 对象引用 ) {
    //异常的解决方案
} catch () {

} finally {
    //最终执行的代码逻辑
}

【例题2】 异常处理举例

package cn.du.ch06;

public class Java02_Exception {
    public static void main(String[] args) {
        /*
         异常处理语法:
         TODO try :尝试
         TODO catch :  捕捉
            捕捉多个异常的时候,需要先捕捉范围小的异常,然后再捕捉范围大的异常
         TODO finally : 最终

         try {
             可能会出现异常的代码
             如果出现异常,那么JVM会将异常进行封装,形成一个具体的异常类,然后将这个异常抛出
             所有的异常对象都可以被抛出
         } catch ( 抛出的异常对象 对象引用 ) {
             异常的解决方案
         } catch () {

         } finally {
            最终执行的代码逻辑
         }
         */
        System.out.println("异常处理【杜老师整理】");
        int i = 0;
        int j = 0;

        try {
            j = 10 / i;
        } catch (ArithmeticException e) {
            System.out.println("  异常消息:"+e.getMessage());
            System.out.println("  异常原因:"+e.getCause());
            e.printStackTrace();
            i = 10;
            j = 10 / i;
        } finally {
            System.out.println("  最终(finally中)执行的代码");
        }

        System.out.println("finally之后的语句:j="+j);
    }
}
图4 异常处理举例
图5 没有异常举例

【例题3】除数为0的算术异常、空指针异常举例

package cn.du.ch06;

public class Java03_Exception {
    public static void main(String[] args) {

        // TODO 异常
        System.out.println("除数为0的算术异常、空指针异常【杜老师整理】");
        // 1. 除数为0的算术异常:java.lang.ArithmeticException
        //   运行期异常  可用if语句
        int i = 0;
        if ( i != 0 ) {
            int j = 10 / i;
        }
//        try {
//            System.out.println(10 / i);
//        } catch (ArithmeticException e) {
//            System.out.println("除数为0的算术异常");
//        }

        // 2 : 空指针异常 : java.lang.NullPointerException
        //     调用了一个为空(null)对象的成员属性或成员方法时,就会发生异常
        User3 user = null;
        if ( user != null ) {
            System.out.println(user.toString());
        }
//        try {
//            System.out.println(user.name);
//            System.out.println(user.toString());
//        } catch (NullPointerException e) {
//            System.out.println("对象为空,需要分析数据为空的原因");
//        }
    }
}
class User3 {
    public static String name = "杜老师";
}
图6 除数为0的算术异常、空指针异常测试之一
图7 除数为0的算术异常、空指针异常测试之二

【例题4】数组索引越界-字符串索引越界异常

package cn.du.ch06;

public class Java04_Exception {
    public static void main(String[] args) {

        // TODO 异常
        // 3. 数组索引越界 : ArrayIndexOutOfBoundsException
        System.out.println("数组索引越界-字符串索引越界【杜老师整理】");
        String[] names = new String[3];
        names[0] = "张三";
        names[1] = "李四";
        names[2] = "王五";
        names[3] = "赵六";
        if ( names.length == 4 ) {
            names[3] = "赵六";
        }
        for ( int i = 0; i < names.length; i++ ) {
            System.out.println(names[i]);
        }
        // 4. 字符串索引越界:StringIndexOutOfBoundsException
        String s = "abc";
        System.out.println(s.charAt(3));
        System.out.println(s.substring(4));
    }
}
图8 数组索引越界-字符串索引越界异常之一
图9 数组索引越界-字符串索引越界异常之二
图10 数组索引越界-字符串索引越界异常之三

【例题5】数值格式化异常-类型转换错误

package cn.du.ch06;

public class Java05_Exception {
    public static void main(String[] args) {
        // TODO 异常
        System.out.println("数值格式化异常-类型转换错误【杜老师整理】");
        // 5. 数值格式化异常:NumberFormatException
        String s = "a123";
        Integer i = Integer.parseInt(s);
        System.out.println("i = "+i);
        // 6 类型转换错误:java.lang.ClassCastException
        Object obj = new User5();
        Emp5 emp = (Emp5)obj;
        if ( obj instanceof Emp5 ) {
            Emp5 emp2 = (Emp5)obj;
        }
    }
}
class User5 {}
class Emp5 {}
图11 数值格式化异常-类型转换错误之一
图12 数值格式化异常-类型转换错误之二
图13 数值格式化异常-类型转换错误之三

【例题6】常见异常

package cn.du.ch06;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.SocketException;
import java.sql.SQLException;

public class Java06_Exception {
    public static void main(String[] args) {

        // TODO 异常
        //IOException  输入或输出异常(即写读异常)
        //SocketException  SOCKET网络连接异常
        //SQLException  SQL数据库请求E异常
        //FileNotFoundException  文件没找到异常
        //ClassNotFoundException  类找不到异常
    }

}
class User6 {
    public void test() {
        // clone方法时Object类中的方法。可以复制当前对象。会发生异常
        try {
            this.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }
}

【例题7】抛出异常

package cn.du.ch06;
public class Java07_Exception {
    public static void main(String[] args) throws Exception {
    //public static void main(String[] args){
        // TODO 异常
        // 可以创建异常对象,并提供异常信息
        // 可以主动抛出异常,使用关键字throw new Exception()
        // 如果方法抛出异常,那么可以使用throws Exception关键字明确方法会抛出异常
        System.out.println("抛出异常throw-throws【杜老师整理】");
        int i = 10;
        int j = 0;
        test(i, j);
    }
    public static void test( int i, int j ) throws Exception {
        try {
            System.out.println(i / j);
        } catch (ArithmeticException e) {
            throw new Exception("除数为0");
        }
    }
}
图14 抛出异常
图15 异常捕获或声明抛出

【例题8】自定义异常

package cn.du.ch06;

public class Java08_Exception {
    public static void main(String[] args) throws Exception {
        // TODO异常
        System.out.println("自定义异常【杜老师整理】");
        String account = "zhangsan";
        String password = "123123";
        try {
            Login(account, password);
        } catch (AccountException accountException) {
            System . out. println("账号不正确,需要重新修正");
        } catch (PasswordException passwordException) {
            System . out. println("密码不正确,需要重新修正");
        } catch (LoginException loginException) {
            System. out. println("其他登录的相关错误,需要确认");
        }
    }

    public static void Login( String account, String password ) {
        if ( !"dzjiang".equals(account) ) {
            throw new AccountException("账号不正确");
        }
        if ( !"123456".equals(password) ) {
            throw new PasswordException("密码不正确");
        }
        System.out.println("登录成功");
    }

}
class AccountException extends LoginException {
    public AccountException(String  message) {
        super (message);
    }
}
class PasswordException extends LoginException {
    public PasswordException(String message) {
        super (message);
    }
}
// TODO自定义异常

class LoginException extends RuntimeException {
    public LoginException(String message) {
        super(message);
    }
}
图16 自定义异常
图17 自定义异常之二
图18 自定义异常之三
图19 ch06 异常源代码截图

返回