JavaSE第六章 异常 Execption

6 第六章异常

6.1 异常

异常的定义

运行时,程序不能正常执行, 即出现了异常.

异常就是有异于常态,和正常情况不一样,有错误出现。在java中,阻止当前方法或作用域的情况,称之为异常。

异常的分类
在这里插入图片描述

Error:是程序中无法处理的错误,表示运行应用程序中出现了严重的错误。此类错误一般表示代码运行时JVM出现问题。通常有Virtual MachineError(虚拟机运行错误)、NoClassDefFoundError(类定义错误)等。比如说当jvm耗完可用内存时,将出现OutOfMemoryError。此类错误发生时,JVM将终止线程。非代码性错误。因此,当此类错误发生时,应用不应该去处理此类错误。

Exception::程序本身可以捕获并且可以处理的异常。比如空指针异常等等 .

运行时异常(不受检异常):RuntimeException类极其子类表示JVM在运行期间可能出现的错误。编译器不会检查此类异常,并且不要求处理异常,比如用空值对象的引用(NullPointerException)、数组下标越界(ArrayIndexOutBoundException)。此类异常属于不可查异常,一般是由程序逻辑错误引起的,在程序中可以选择捕获处理,也可以不处理。

编译时异常(受检异常):Exception中除RuntimeException极其子类之外的异常。编译器会检查此类异常,如果程序中出现此类异常,比如说IOException,必须对该异常进行处理,要么使用try-catch捕获,要么使用throws语句抛出,否则编译不通过。

常见的异常

public static void main(String[] args) {
    
    
        // 内存不够  
        List<Random> list = new ArrayList<>();
        for (;;){
    
    
            list.add(new Random());
        }
        
        //算术异常
        int a = 10;
        int b = 0;
        System.out.println(a/b);

        //类型转换异常
        String s = "ssss";
        Object obj = s;
        Integer intInt = (Integer) obj;

        //数组下标越界
        int[] ints = new int[5];
        System.out.println(ints[5]);
        
        //空指针异常
        String str = null;
        System.out.println(str.length());
    }

异常的处理

抛出异常:throw,throws

捕获异常:try,catch,finally

抛出异常throw

throw用在方法内,用来抛出一个异常对象,将这个异常对象传递到调用者处,并结 束当前方法的执行。

使用的格式:

throw new 异常类名(参数);

示例:

public class DemoThrow {
    
    
    public static void main(String[] args) {
    
    
      int a =   DemoThrow.div(4,0);
      System.out.println(a);
    }
   public static int div(int a,int b)
   {
    
    
            if(b==0)
              throw new ArithmeticException("异常信息:除数不能为0");//抛出具体问题,编译时不检测
            return a/b;
     }
}

声明抛出异常throws

运用于方法声明之上,用于表示当前方法不处理异常,而是提醒该方法的调用者来处理异常

使用格式:

修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2 ... { }

示例

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class DemoThrows {
    
    
    public static void main(String[] args) throws FileNotFoundException{
    
    
        readFile();
    }
    public static  void readFile() throws FileNotFoundException {
    
    
        InputStream is = new FileInputStream("E:/iodemo/ch01.txt");
    }
}

try代码块

try {
    
    
   ...  //监视代码执行过程,一旦返现异常则直接跳转至catch,
        // 如果没有异常则直接跳转至finally
} catch (SomeException e) {
    
    
    ... //可选执行的代码块,如果没有任何异常发生则不会执行;
        //如果发现异常则进行处理或向上抛出。
} finally {
    
    
    ... //必选执行的代码块,不管是否有异常发生,
        // 即使发生内存溢出异常也会执行,通常用于处理善后清理工作。
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class DemoTryCatch {
    
    
    public static void main(String[] args) {
    
    
        //捕获异常
        try {
    
    
            //可能产生异常的代码
            readFile();
        } catch (FileNotFoundException e) {
    
    
            //异常的处理逻辑,将异常记录日志,异常封装后显示
          System.out.println("系统找不到指定的路径");
        }
        System.out.println("后续代码");
    }

    public static  void readFile() throws FileNotFoundException {
    
    
        InputStream is = new FileInputStream("E:/iodemo/ch01.txt");
    }
}
public static int textEsception1(){
    
    
        /*
            发生异常时,会先执行catch块,在执行finally块, 然后再 执行catch中的return语句
                                     如果finally中 有return语句 则直接结束函数并返回.
         */
        try {
    
    
            int a = 10;
            int b = 0;
            System.out.println(a/b);
        }catch (ArithmeticException e){
    
    
            System.out.println("算术错误");
            return 0;
        }finally {
    
    
            System.out.println("sssssssssssssss");  //finally 不论是否捕捉到异常 都会执行
//            return 2;
        }
        System.out.println("发生异常时, try-catch外的代码可以继续执行");
        return 1;
    }

自定义异常

除了JDK定义好的异常类外,在开发过程中根据业务的异常情况自定义异常类。

package com.example.springbootmybatis;
/**
 * 自定义异常类
 * 用户不存在异常信息类
 */

public class UserNotExistsException extends RuntimeException{
    
    

    public UserNotExistsException() {
    
    
        super();
    }

    public UserNotExistsException(String message) {
    
    
        super(message);
    } 	

猜你喜欢

转载自blog.csdn.net/qq_37079157/article/details/109860642