异常的引入
在使用计算机语言进行项目开发的过程中,即使程序员把代码写得尽善尽美,在系统的运行过程中仍然会遇到一些问题,因为很多问题不是靠代码能够避免的,比如:客户输入数据的格式,读取文件是否存在,网络是否始终保持通畅等等。
1.定义
- 异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。
2.异常的分类
从程序执行过程可分为两类
- 编译时异常:执行javac.exe命名时,可能出现的异常;
是指编译器不要求强制处置的异常。一般是指编程时的逻辑错误,是程序员应该积极避免其出现的异常。java.lang.RuntimeException类及它的子类都是运行时异常。 - 运行时异常:执行java.exe命名时,出现的异常。
是指编译器要求必须处置的异常。即程序在运行时由于外界因素造成的一般性异常。编译器要求Java程序必须捕获或声明所有编译时异常。
2.1运行时异常举例
//ArithmeticException
public void test6(){
int a = 10;
int b = 0;
System.out.println(a / b);
}
//InputMismatchException
public void test5(){
Scanner scanner = new Scanner(System.in);
int score = scanner.nextInt();
System.out.println(score);
scanner.close();
}
//NumberFormatException
public void test4(){
String str = "123";
str = "abc";
int num = Integer.parseInt(str);
}
//ClassCastException
public void test3(){
Object obj = new Date();
String str = (String)obj;
}
//IndexOutOfBoundsException
public void test2(){
//StringIndexOutOfBoundsException
String str = "abc";
System.out.println(str.charAt(3));
}
2.2编译时运行异常举例
public void test7(){
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
fis.close();
}
异常处理机制
一:异常处理的两种方式
- 方式一:try-catch-finally
- 方式二:throws + 异常类型
try-catch-finally处理模式
//异常处理是通过try-catch-finally语句实现的。
try{
......//可能产生异常的代码
}catch(ExceptionName1e){
......//当产生ExceptionName1型异常时的处置措施
}catch(ExceptionName2e){
.....//当产生ExceptionName2型异常时的处置措施
}[finally{
......//无论是否发生异常,都无条件
}]
- try
捕获异常的第一步是用try{...}语句块选定捕获异常的范围,将可能出现异常的代码放在try语句块中。 - catch
在catch语句块中是对异常对象进行处理的代码。每个try语句块可以伴随一个或多个catch语句,用于处理可能产生的不同类型的异常对象。
常用的异常对象处理的方式: ① String getMessage() ② printStackTrace()
throws + 异常类型处理方式
如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何处理这种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。
注意:
"throws + 异常类型"写在方法的声明处。指明此方法执行时,可能会抛出的异常类型。
一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象,此对象满足throws后异常类型时,就会被抛出。异常代码后续的代码,就不再执行!
importjava.io.*;
public class ThrowsTest {
public static void main(String[] args) {
ThrowsTest t= newThrowsTest();
try{
t.readFile();
} catch(IOException e) {
e.printStackTrace();
}
}
public void readFile() throws IOException {
FileInputStream in= newFileInputStream("atguigushk.txt");
int b;
b= in.read();
while(b!= -1) {
System.out.print((char) b);
b= in.read();
}
in.close();
}
}
手动抛出异常
Java异常类对象除在程序执行过程中出现异常时由系统自动生成并抛出,也可根据需要使用人工创建并抛出。
首先:首先要生成异常类对象,然后通过throw语句实现抛出操作(提交给Java运行环境)。
IOExceptione=newIOException();
throwe;
可以抛出的异常必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:
throw new String("want to throw");
用户自定义异常
- 一般地,用户自定义异常类都是RuntimeException的子类。
- 自定义异常类通常需要编写几个重载的构造器。
- 自定义异常需要提供serialVersionUID
- 自定义的异常通过throw抛出。
- 自定义异常最重要的是异常类的名字,当异常出现时,可以根据名字判断异常类型。
用户自定义异常类MyException,用于描述数据取值范围错误信息。用户自己的异常类必须继承现有的异常类。
class MyException extendsException {
static final long serialVersionUID= 13465653435L;
private int id number;
public MyException(String message, intid) {
super(message);
this.idnumber= id;
}
public int getId() {
return idnumber;
}
}
public class MyExpTest {
public void regist(int num) throws MyException {
if(num< 0){
throw new MyException("人数为负值,不合理", 3);
}else {
System.out.println("登记人数"+ num);
}
}
public void manager() {
try{
regist(100);
} catch(MyException e) {
System.out.print("登记失败,出错种类"+ e.getId());
}
System.out.print("本次登记操作结束");
}
public static void main(String args[]) {
MyExpTest t= newMyExpTest();
t.manager();
}
}