异常:
       异常就是Java程序在运行过程中出现的错误

一、异常及错误:

Throwable 类是 Java 语言中所有错误或异常的超类
Throwable 有两个子类:

           Error Exception

1、Error:严重问题,比如内存溢出
2、Exception :问题
         Exception 又分为 编译期问题 运行期问题
(1)运行期问题:RuntimeException 代码不严谨出现的
(2)编译期问题:不是 RuntimeException 的异常,必须处理的问题

下面是一段抛出异常的代码:


public class ExceptionDemo {
	public static void main(String[] args) {
		
		int m = 5;
		int n = 0;
		System.out.println(m/n);
		
		System.out.println("这里出现了异常");
	}
}

结果:

他只是把异常输出在了控制台,但是却没有进行处理,也没有继续进行程序,这肯定不是我们想要的

二、异常的处理方案:

1、try...catch...finally:

try...catch...finally 的格式:

try{

     可能出现问题的代码

}catch(异常名 变量){

     针对问题的处理

}finally{

     用于释放资源

}

2、throws:

上面出现异常代码的处理:


public class ExceptionDemo {
	public static void main(String[] args) {
		
		int m = 5;
		int n = 0;
		try {
			System.out.println(m/n);
		}catch(ArithmeticException e){
			System.out.println("除数不能为0");
		}
		
		System.out.println("这里出现了异常");
	}
}

结果:

这样就好多了,可以在catch中提示异常,剩下的程序也可以正常运行

throws:

       定义功能方法时,需要把出现的问题暴露出来让调用者去处理,就可以通过throws方法来标识

例子:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExceptionDemo {
	public static void main(String[] args) {
		//用try...catch处理抛出的异常
		try {
			method();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	public static void method() throws ParseException { //抛出异常
		String s = "2019-8-2";
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-mm-dd");
		Date d = sd.parse(s);
		System.out.println(d);
	}
}

throw:

        在功能内部出现某种情况,程序不能继续运行,需要进行跳转时,就用throw把异常对象抛出

throw的使用:


public class ExceptionDemo {
	public static void main(String[] args) {
		method();
	}
	public static void method() { 
		int m = 10;
		int n = 0;
		if(n == 0) {
			throw new ArithmeticException();
		}else {
			System.out.println(m/n);
		}
	}
}

3、throws 和 throw 的区别:

(1)throws :

         用在方法声明后面,跟的是异常类名

         可以跟多个异常类名,用逗号隔开

         表示抛出异常,由该方法的调用者来处理

         throws表示出现异常的一种可能性,并不一定会发生异常

(2)throw :

         用在方法体内,跟的是异常对象名

         只能抛出一个异常对象名

         表示抛出异常,由方法体内的语句处理

         throw是抛出了异常,执行throw则一定跑出来某种异常