JAVA基础课程
第十五天 关于异常
异常的概述和异常体系结构
(1)异常,在Java中,将程序执行中发生的不正常情况称为“异常”。语法错误和逻辑错误不叫异常
(2)Java中的异常分为两类
①Error:Java虚拟机无法解决的严重问题。如JVM系统内部错误,资源耗尽等严重情况。比如:StackOverflowError栈溢出和OutOfMemoryError(OOM)堆溢出。一般不编写针对性代码处理
②Exception:因为编程错误或者偶然的因素导致的一般性问题,可以使用针对性代码进行处理。比如:空指针异常等
(3)体系结构
java,lang,Throwable
|–Error
|–Exception
|–编译时异常(checked)
|–IOException
|–ClassNotFoundException
|–运行时异常
|–NullPointerException
|–ArrayIndexOutOfBoundsException
|–ClassCaseException
|–NumberFormatException
|–InputMismatchException
|–ArithmeticException
(4)常见异常的代码
package com.test.course.exceptiontest;
import java.util.Date;
/**
* 〈常见异常〉
* @author PitterWang
* @create 2020/5/2
* @since 1.0.0
*/
public class ExceptionAll {
public static void main(String[] args) {
/***
* Exception in thread "main" java.lang.StackOverflowError
* main(args);
*/
/***
* Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
* Integer[] i = new Integer[1024*1024*1024];
*/
/***
* java.lang.ArrayIndexOutOfBoundsException:
* Integer[] i = new Integer[]{1,2,3};
* System.out.println(i[3]);
*/
/***
* java.lang.NullPointerException
* Date date = null;
* System.out.println(date.toString());
*/
/**
* java.lang.ArithmeticException: / by zero
* int i = 3/0;
*/
}
}
异常处理机制
抛抓模型
过程一:“抛” 程序执行中,一旦发生异常,就会在异常代码处生成一个对应异常类的对象,并将次对象抛出。一旦抛出对象后其他代码就不执行了
过程二:"抓"可以理解为抛出异常的处理方式
(1)try-catch-finally
①格式
try {
}catch (异常类型1 变量名1){
}catch (异常类型2 变量名2){
}catch (异常类型3 变量名3){
}finally {
//一定会执行的代码
}
②说明
1》finally是可选的
2》使用try将可能出现的异常包装起来,在执行过程中一旦出现异常就生成一个异常类对应的对象,根据次对象的类型,去catch中进行匹配,一旦匹配到了某个catch时,就进行异常处理。一旦处理完iu退出当前try-catch结构,继续执行后边代码
3》catch如果没有子父关系,则没无所谓,如果满足子父关系,则要求子类在父类之上,否则报错
4》异常对象处理的方式:String getMessage() 或者 printStackTrace()
(2)throws + 异常类型
①格式:写在方法声明处
方法名(参数) throws 异常类型
②说明:
1》指明此方法执行时,可能会抛出异常类型,一旦方法体执行中出现异常,会在异常代码处抛出一个异常对象,次对象满足throws 异常类型时,就会抛出,异常子厚的diamagnetic不在执行
(3)如何选择try-catch-finally还是throws + 异常类型
①如果父类方法中被重写的方法没有throws 方法处理异常,则子类重写的方法也不能使用throws 。必须用try-catch-finally结构
②根据实际开发中的需求选择
手动抛出异常
throw进行手动抛出异常
package com.test.course.exceptiontest;
/**
* 〈异常〉
* @author PitterWang
* @create 2020/5/2
* @since 1.0.0
*/
public class ExceptionTest {
public static void main(String[] args){
regit(-1);
}
public static void regit(int i){
if(i > 0){
System.out.println("没毛病老铁");
}else{
throw new RuntimeException("i必须大于0");
}
}
}
用户自定义异常类
package com.test.course.exceptiontest;
/**
* 〈自定义抛出类〉
*
* 1,继承现有异常结构RuntimeException
* 2,提供全局常量serialVersionUID
* 3,提供重载构造器
* @author PitterWang
* @create 2020/5/2
* @since 1.0.0
*/
public class MyException extends RuntimeException{
static final long serialVersionUID = -1;
public MyException(){
}
public MyException(String message){
super(message);
}
}