Java Exception 异常处理
一、定义
异常(Exception) : 是指程序运行时出现的非正常情况,是特殊的运行错误对象,对应着Java语言特定的运行错误处理机制。
二、两大常见的异常类型
• RuntimeException(运行时异常):主要包括“错误的类型转换”、“数组下标越界”、“数组越界”和“空指针”等,这种RuntimeException往往是由于程序的不正确导致的;
•Non-RuntimeException(非运行时异常):主要包括“从一个不存在的文件中读取数据”、“越过文件结尾继续读取”、“连接一个不存在的URL”等,这种Non-RuntimeException一般是在编译器编译时产生的,通常由环境因素造成,而不是程序本身的作用导致的,例如:IOException。
三、异常处理的两种方式
①用 try……catch……(finally) 捕获异常
try{
可能遇到的异常
}
catch{
处理异常的方法
}
finally{
程序输出的内容
}
(注意:①try 在程序中不能单独使用,每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象;②finally语句为异常处理提供了一个统一的出口,无论在try代码块中是否发生了异常,finally块中的语句都会被执行,即finally语句无论遇到什么异常都会输出。)
②用 throws 抛出异常
public void readFile (Srting file) throws FileNotFoundException{ } //格式:返回类型 + 方法名(参数列表)+ throws + 异常类型列表
四、举例说明
eg: 定义一个整型的数字69,判断它是否与ASCII码表中的字符‘T’是否相等,若不等于‘T’就继续执行代码,输出69所对应的字符。在这个判断的过程可能会出现IOException,我们就通过这个例子来比较一下异常处理的这两种方式。
①用 try......catch......(finally) 捕获异常
import java.io.IOException; public class ExceptionTest { public static void read( ) { int a = 69; try { while((char)a != \'T\') { //判断69对应的字符是否等于‘T’,若不等则继续执行代码 System.out.println((char) a); a = System.in.read( ); //从a中读取字符 } } catch(IOException e){ System.out.println("ExceptionTest"); } } public static void main(String[] args) { ExceptionTest.read( ); } }
②用 throws 抛出异常 import java.io.IOException; public class ExceptionTest { public static void read( ) throws IOException { int a = 69; while((char)a != \'T\') { //判断69对应的字符是否等于‘T’,若不等则继续执行代码 System.out.println((char) a); a = System.in.read( ); //从a中读取字符 throw new IOException(); //在方法体中,抛出异常的throw不需要加s(该异常对象可省略不写 } System.out.println("ExceptionTest"); } public static void main(String[] args) throws IOException { ExceptionTest.read( ); } }