java基础知识点05_异常

本文深入讲解Java中的异常处理机制,包括异常的超类Throwable,如何使用try-catch-finally进行异常捕获,开发者如何主动抛出异常,以及如何创建自定义异常。通过实例演示了系统自动抛出和开发者主动抛出异常的情况,并展示了自定义异常的实现。

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

java基础知识点05_异常


异常的超类:java.lang.Throwable

在这里插入图片描述

异常处理机制

捕获:

int a = 1;
int b = 0;
try {
	System.out.println(a/b);
} catch (ArithmeticException e) {
	System.out.println("程序出现异常:变量b不能为0");
}finally {
	System.out.println("finally....");
}
public static void main(String[] args) {
	try {
		a();
	} catch (StackOverflowError e) {
		System.out.println("程序出现错误:StackOverflowError");
	}finally {
		System.out.println("finally....");
	}
}
	
public static void a() {
	b();
}
	
public static void b() {
	a();
}

抛出:

  • 系统自动抛出:
public static void main(String[] args) {
	System.out.println(1/0);
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
  • 开发者主动抛出:
public static void main(String[] args) {
	int a = 1;
	int b = 0;
	if(b==0) {
		throw new ArithmeticException();
	}else {
		System.out.println(a/b);
	}	
}
Exception in thread "main" java.lang.ArithmeticException

自定义异常:

public class MyException extends Exception{
	
	//传递数字,如果数字大于10,则抛出异常
	private int detail;

	public MyException(int a) {
		this.detail = a;
	}
	
	@Override
	public String toString() {
		return "MyException{"
				+ "detail=}"
				+ detail
				+ "}";
	}
	
}


public class demo01 {

	static void test(int a) throws MyException {
		if(a>10) {
			throw new MyException(a);
		}
		System.out.println("okkkkkkkkkkk");
	}
	
	public static void main(String[] args) {
		try {
			test(23);
		} catch (MyException e) {
			System.out.println(e);
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值