java TryCatch的简单用法以及异常分类图解

本文深入探讨了Java中常见的异常处理机制,包括空指针异常、算数异常、数组下标越界异常及类型转换异常。通过具体代码示例,详细解释了如何使用try/catch语句来捕获和处理这些异常,为Java开发者提供了实用的异常处理指南。

java Try/Catch的简单用法

public class TestTryCatch {

	public static void main(String[] args) {

		nullPointExcertion();
		arithmeticException();
		arrayIndexOutOfBoundsException();
		classCastException("6");
		
	}

	// 空指针异常
	public static void nullPointExcertion() {

		try {
			String name = null;
			
			System.out.println(name.getClass());
			

		} catch (NullPointerException e) {

			System.out.println("这个是空指针异常");
		}

	}

	// 算数异常
	public static void arithmeticException() {
		try {
			int i = 0;
			int j = 10 / i;
			System.out.println(j);

		} catch (ArithmeticException e) {

			System.out.println("这个是算数异常");

		}

	}

	// 数组下标越界
	public static void arrayIndexOutOfBoundsException() {

		try {
			int[] arr = { 1, 2, 3, 4, 5 };

			System.out.println(arr[5]);

		} catch (ArrayIndexOutOfBoundsException e) {

			System.out.println("这个是数组下标越界异常");
		}
	}

	// 类型转换异常
	public static void classCastException(Object str) {

		try {
			
			Integer i = (Integer)str;
			
		} catch (ClassCastException e) {

			System.out.println("这个是类型转换异常");
		}

	}

}

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值