Java——异常&&错误-Throwable

文章详细介绍了Java中的异常体系,包括Error和Exception的分类,以及如何处理这些异常。Error是JVM内部错误,如栈溢出和内存溢出,无法恢复。Exception分为受检异常和运行时异常,运行时异常如空指针和算术异常。Java异常处理包括try-catch-finally块,throws关键字用于方法上抛出异常,而throw则用于手动抛出异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误–异常

Java中所有异常和错误的父类:Throwable

Throwable:

  1. Error(错误)
  2. Exception(异常)

Error – 错误

错误出现的情况:

JVM系统内部错误或资源耗尽等严重情况-属于JVM需要负担的责任,这一类异常事件无法恢复或不可能捕获,将导致应用程序中断

  1. 栈内存溢出的错误(StackOverflowError)
public class Test {
    /**
    *方法的递归导致的栈内存溢出的异常
    *
    */
	public static void main(String[] args) {
		//StackOverflowError栈内存溢出的异常
		method();
	}
	
	public static void method() {
		method();
	}
}
  1. 内存溢出异常(OutOfMemoryError)
public class Test {
	public static void main(String[] args) {
        //500000000超出了内存的最大长度
		String[] ss = new String[500000000];
		System.out.println(ss);
        
        
        ArrayList<byte[]> list = new ArrayList<>();

		while (true) {
			//死循环,循环创建byte[]数组存入ArrayList集合中,超出了集合存储范围导致内存溢出异常
			byte[] bs = new byte[1024];
			list.add(bs);
		}
        
	}

}

Exception – 异常

异常出现的情况:

其它因编程错误或偶然的外在因素导致的 一般性问题。这类异常得到恰当的处理时,程序有机会恢复正常运行状况。

RuntimeException – 运行时异常

RuntimeException – 运行时异常:非受检性异常,编译器不要求强制处置的异常。一般是指编程时的逻辑错误。是程序员应该积极避免其出现的异常

  1. ArithmeticException – 算术异常
public class Test {
	public static void main(String[] args) {
		// 10/0 -- 算数异常
		System.out.println(10 / 0);
	}

}

  1. NullPointerException – 空指针异常
public class Test {
	
	 * RuntimeException/运行时异常:非受检性异常,编译器不要求强制处置的异常。
	 * 							一般是指编程时的逻辑错误。是程序员应该积极避免其出现的异常
	 * 
	 */
	public static void main(String[] args) {

		//NullPointerException空指针异常
         //调用方法时传入参数类型错误
		method(null);
	}
	
	public static void method(String string) {
		
		System.out.println(string.length());
	}

}

  1. ArrayIndexOutOfBoundsException – 数组下标越界异常
public class Test {
	public static void main(String[] args) {

		int[] i = {1,2,3,4,5,6};
		
		//ArrayIndexOutOfBoundsException数组下标越界异常
		System.out.println(i[6]);
	}

}

  1. ClassCastException – 类型转换异常
public class Test {
	public static void main(String[] args) {
		Object obj = new Integer(100);
		Double double1 = (Double) obj;
		
		//ClassCastException类型转换异常
		System.out.println(double1);
	}
}

IOException – 读写时异常

一般性异常:受检性异常,编译器要求必须处置的异常。指的是程序在运行时由于外界因素造成的一般性异常。

创建一个文件–DBConfig.properties

username=xiaohong
password=123456
import java.io.IOException;
import java.util.Properties;

public class Test {
    
	//@throws IOException--读写异常(输出或者输入)
	public static void main(String[] args) throws IOException {
		// 创建配置文件类的对象
		Properties p = new Properties();

		// 将文件加载到对象中,如果文件名输入错误就会抛出异常
		p.load(Test01.class.getClassLoader().getResourceAsStream("DBConfig.properties"));

		String username = p.getProperty("username");
		String password = p.getProperty("password");

		System.out.println(username + " -- " + password);
	}
}

Java异常类的处理

Java异常类的处理机制:

Java程序在执行过程中如果出现异常会自动创建异常类对象,该异常类对象将被自动交给JVM(throw);当JVM接收到异常对象时,会寻找能够处理该异常的代码;

  1. 如果找到了就把当前异常交给其处理,这一过程叫做捕获异常(catch)
  2. 没找到、运行时系统将会终止,相对应的Java程序也将退出

Java处理异常的能力

1. try…catch

语法结构:

try{
    //可能发生异常的代码
}catch(异常类型 e){
    //捕获异常/处理异常
}finally{
    //不管是否发生异常,都会执行的代码
}

捕获并处理单个异常:

import java.util.Scanner;
public class Test01 {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);

		System.out.println("请输入第一个数字:");
		int a = scan.nextInt();
		System.out.println("请输入第二个数字:");
		int b = scan.nextInt();

		try {
			System.out.println("111");
			System.out.println(a / b);
            //注意:如果在这捕获到异常那么程序会直接进入catch(处理异常环节),不会执行下面一行代码
            
			System.out.println("222");

		} catch (ArithmeticException e) {
			System.out.println("处理异常");

		} finally {
			scan.close();
		}

	}

}

2. Throws – 抛出异常

理解:方法抛出异常,让调用方去处理

语法结构:

public void method() throws 异常类型,异常类型,...{}

例子:

import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		
		
		try {
			method01();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void method01() throws ClassNotFoundException{
		method02();
	}
	
	public static void method02() throws ClassNotFoundException{
		method03();
	}
	
	public static void method03() throws ClassNotFoundException{
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("请输入一个类的路径:");
		String path = scan.next();
		Class<?> clazz = Class.forName(path);//通过路径获取该类的class对象
		System.out.println(clazz.getName());
		scan.close();
		
	}
	
}

3. throw – 手动抛出异常

语法结构:

throw new 异常类型();

例子:

创建MyException类:

package com.qf.exception03;

public class MyException extends RuntimeException{

	@Override
	public String toString() {
		return "除数不能为0的异常~~~";
	}
}

创建测试类:

import java.util.Scanner;
public class Test {

	public static void main(String[] args) {
		
		Scanner scan = new Scanner(System.in);
		
		System.out.println("请输入第一个数字:");
		int a = scan.nextInt();
		System.out.println("请输入第二个数字:");
		int b = scan.nextInt();
		
		try {
			if(b == 0){
				//手动抛出异常
                //调用MyException()
				throw new MyException();
			}
		} catch (MyException e) {
			b = 1;
		}
		
		System.out.println(a/b);
		
		scan.close();
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值