Java自定义异常处理

来源:互联网 发布:无线网络规划仿真软件 编辑:程序博客网 时间:2024/05/16 08:27

在Java中,我们常常会遇到需要自定义异常处理的情况。下面通过一个例子来说明如何自定义异常。

假设这样一个情景,我们需要从文本文件中读取信息到数组,每一行对应一条记录。如果文本文件的行数超出了数组大小,则显示警告,并停止继续读入。例如,我们要读取的是学生成绩信息(学生id和5次考试成绩),文本文件有80行,但是数字只开了40,则在读取第41行时,抛出异常,只保留前40个数据。

首先定义异常类DataLoadException,继承自Exception类。如果没有特殊要求,类中可以不添加任何变量和方法。

1
2
3
publicclass DataLoadException extendsException{
      
}

接下来在需要抛出异常的地方写上创建DataLoadException对象,并使用throw关键字抛出。

在这个情境中,我们使用count计数读取的行数。当读取的行数超过数组(students)大小时,抛出异常。

1
2
3
if(count >= students.length){
    thrownew DataLoadException();
}

接下来,只要向处理一般的异常一样,catch或者继续throw即可。

 


 

以下是完整代码,仅供参考:

DataLoadException类

1
2
3
4
@SuppressWarnings("serial")
publicclass DataLoadException extendsException{
      
}

Student类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
publicclass Student {
 
    privateint id;
    privateint[] scores = newint[5];
     
    publicStudent(intid) {
        this.id = id;;
    }
     
    publicvoid setScore(intindex, intscore){
        scores[index] = score;
    }
 
}

Util类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
publicclass Util {
 
    @SuppressWarnings("resource")
    publicstatic Student[] readFile(String filename, Student[] students) throwsNumberFormatException, IOException{
        ArrayList<Student> studentList = newArrayList<Student>();
        File file = newFile(filename);
        FileReader fileReader = null;
        BufferedReader bufferReader = null;
        try{
            fileReader = newFileReader(file);
            bufferReader = newBufferedReader(fileReader);
            String line = null;
            for(intcount = 0; (line = bufferReader.readLine()) != null; count++){
                if(count >= students.length){
                    thrownew DataLoadException();
                }
                String[] contents = newString[6];
                StringTokenizer stringTokenizer = newStringTokenizer(line);
                for(inti = 0; stringTokenizer.hasMoreTokens(); i++){
                    contents[i] = newString(stringTokenizer.nextToken());
                }
                Student student = newStudent(Integer.parseInt(contents[0]));
                for(inti = 0; i < 5; i++){
                    student.setScore(i, Integer.parseInt(contents[i+1]));
                }
                studentList.add(student);
            }
            bufferReader.close();
        }catch(DataLoadException e) {
            System.out.println("WARNING! Cannot load more data to array (length: " + students.length + ")\n");
        }
        return(Student[]) studentList.toArray(newStudent[studentList.size()]);
    }
 
}

 

注:原文见我的博客《Java自定义异常处理》

0 0
原创粉丝点击