⑬Java SE知识点回顾与小结(异常处理)

本文深入讲解Java异常处理机制,包括检查性异常、运行时异常及错误的区别与处理方式。通过实例演示如何捕获异常、声明自定义异常,帮助读者更好地理解和运用Java异常处理。

Java 异常处理

异常是程序中的一些错误,但并不是所有的错误都是异常,并且错误有时候是可以避免的。

比如说,你的代码少了一个分号,那么运行出来结果是提示是错误 java.lang.Error;如果你用System.out.println(11/0),那么你是因为你用0做了除数,会抛出 java.lang.ArithmeticException 的异常。

异常发生的原因有很多,通常包含以下几大类:

  • 用户输入了非法数据。
  • 要打开的文件不存在。
  • 网络通信时连接中断,或者JVM内存溢出。

这些异常有的是因为用户错误引起,有的是程序错误引起的,还有其它一些是因为物理错误引起的。-

要理解Java异常处理是如何工作的,你需要掌握以下三种类型的异常:

  • **检查性异常:**最具代表的检查性异常是用户错误或问题引起的异常,这是程序员无法预见的。例如要打开一个不存在文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。
  • 运行时异常: 运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
  • 错误: 错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,它们在编译也检查不到的。
/*		Throwable
 * 	    /		\
 * Error		Exception
 * 			 /			\
 * 			Checked		Runctime
 * 			Exception   Exception
 * 
 * Error:错误,一般指虚拟机生成并脱出的,如jvm内存溢出
 * Exception: 
 * 	编译时异常|检查时异常: 编译的时候就会发生异常,如果不处理无法运行
 * 	运行时异常: 程序运行期间发生的异常,编译没有问题,一般通过增强程序的健壮性 (if..else)处理
 * 
 * 如果出现异常:不处理都无法执行后续的代码
 * 
 * 常见的运行时异常:
 * 	1.空指针 NullPointerException
 * 	2.数组下标越界  ArrayIndexOutOfBoundsException
 * 	3.数组长度负数异常 NegativeArraySizeException
 *  4.数学异常  ArithmeticException
 *  5.数字转换异常 NumberFormatException
 *  6.类型转换异常  ClassCastException
 *  7.文件未找到异常  FileNotFoundException
 */
编译时异常:
public class ExceptionDemo01 {
	public static void main(String[] args) {
		//1.空指针 NullPointerException
		int[] arr=null;
		//增强程序的健壮性
		/*if(arr!=null){
			System.out.println(arr.length);
		}*/
		
		
		try{
			System.out.println(arr.length);
		}catch(NullPointerException e){
			System.out.println(e.getMessage());
		}
		
		
		//2.数组下标越界  ArrayIndexOutOfBoundsException
		/*arr=new int[5];
		System.out.println(arr[5]);*/
		//3.数组长度负数异常 NegativeArraySizeException
		//arr=new int[-5];
		//4.数学异常  ArithmeticException
		//System.out.println(5/0);
		
		//String str="abc";
		//System.out.println(Integer.valueOf(str));
		//编译时异常
		//InputStream is=new FileInputStream("D:/test.txt");
	}
}

捕获异常

使用 try 和 catch 关键字可以捕获异常。try/catch 代码块放在异常可能发生的地方。

try/catch代码块中的代码称为保护代码,使用 try/catch 的语法如下:

/*
 * throw 是制造异常    注意与throws抛出异常的区别
 * 异常的处理方式:
 * 	抛出异常:throws
 * 		遇到了异常不处理,向上一层抛出,在方法内部抛出到方法上面,谁调用方法谁处理
 * 	捕获异常:try..catch 
 * 		try{
 * 			可能会出现异常的代码
 * 		}catch(要捕获的异常的数据类型  变量名){
 * 			如果出现异常要执行的代码
 * 		}catch(要捕获的异常的数据类型  变量名){
 * 			如果出现异常要执行的代码
 * 		}
 * 			...
 * 		catch(Exception e){
 * 			如果不是以上异常,执行这里的代码
 * 		}finally{
 * 			一般会定义一些资源的关闭..
 * 		}
 * 
 *   注意:
 *   	1.如果使用try,必须跟catch
 *   	2.catch可以有一个可以存在多个
 *   	3.接收大范围类型的catch要放在最后,否则编译出错,因为代码从上倒下执行
 *   	4.finally最终的,无论是否出现异常,都会执行的代码
 *   	5.try中的内容,出现异常了,执行的对应的catch,try中的内容不会继续向下执行了
 * 
 */
public class ExceptionDemo02 {
	public static void main(String[] args){
		try{
			test();
			int[] arr=new int[-5];
			System.out.println(5/0);
			System.out.println("没有出现异常");
		}catch(FileNotFoundException e){
			//e.printStackTrace();  
			System.out.println("出现了文件未找到异常");
		}catch(ArithmeticException e){
			System.out.println("数学异常,分母为0");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			System.out.println("最后肯定会执行的代码...");
		}
		System.out.println("继续向下执行...");
		
	}
	
	static void test() throws FileNotFoundException{
		//throw new FileNotFoundException();
		InputStream is=new FileInputStream("D:/test.txt");
	}
}

声明自定义异常

在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。

  • 所有异常都必须是 Throwable 的子类。
  • 如果希望写一个检查性异常类,则需要继承 Exception 类。
  • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

可以像下面这样定义自己的异常类:

class MyException extends Exception{
}
实例:
//测试
public class DefinedException03 {
	public static void main(String[] args) {
		Person p=new Person();
		p.setName("小白");
		try{
			p.setAge(-10);
		}catch(AgeException e){
			try {
				p.setAge(18);
			} catch (AgeException e1) {
				e1.printStackTrace();
			}
			System.out.println(e.getMessage());
		}
		System.out.println(p);
	}
}

//自定义异常类    AgeException继承Exception(编译时异常)
class AgeException extends Exception{
//	String message;  //异常信息
	
	public AgeException(){}
	
	public AgeException(int age){
//		this.message=age+"年龄不合法";
		super(age+"年龄不合法");
	}
	
	
	/*public String getMessage(){
		return message;
	}*/
}

//定义javabean类
class Person{
	private String name;
	private int age;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}

	//alt+shift+o-->enter
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	//alt+shift+s-->r-->tab-->enter-->shift+tab-->enter
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}
	//在javabean类中定义setAge,当年龄小于等于0或大于等于150时 抛出此异常
	public void setAge(int age) throws AgeException {
		if(age<=0 || age>=150){
			//System.out.println("年龄不合法");
			throw new AgeException(age);
		}
		this.age = age;
	}

	//alt+shift+s-->s->enter
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值