Java自定义异常处理
来源:互联网 发布:无线网络规划仿真软件 编辑:程序博客网 时间:2024/05/16 08:27
在Java中,我们常常会遇到需要自定义异常处理的情况。下面通过一个例子来说明如何自定义异常。
假设这样一个情景,我们需要从文本文件中读取信息到数组,每一行对应一条记录。如果文本文件的行数超出了数组大小,则显示警告,并停止继续读入。例如,我们要读取的是学生成绩信息(学生id和5次考试成绩),文本文件有80行,但是数字只开了40,则在读取第41行时,抛出异常,只保留前40个数据。
首先定义异常类DataLoadException,继承自Exception类。如果没有特殊要求,类中可以不添加任何变量和方法。
1
2
3
public
class
DataLoadException
extends
Exception{
}
接下来在需要抛出异常的地方写上创建DataLoadException对象,并使用throw关键字抛出。
在这个情境中,我们使用count计数读取的行数。当读取的行数超过数组(students)大小时,抛出异常。
1
2
3
if
(count >= students.length){
throw
new
DataLoadException();
}
接下来,只要向处理一般的异常一样,catch或者继续throw即可。
以下是完整代码,仅供参考:
DataLoadException类
1
2
3
4
@SuppressWarnings
(
"serial"
)
public
class
DataLoadException
extends
Exception{
}
Student类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public
class
Student {
private
int
id;
private
int
[] scores =
new
int
[
5
];
public
Student(
int
id) {
this
.id = id;;
}
public
void
setScore(
int
index,
int
score){
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
public
class
Util {
@SuppressWarnings
(
"resource"
)
public
static
Student[] readFile(String filename, Student[] students)
throws
NumberFormatException, IOException{
ArrayList<Student> studentList =
new
ArrayList<Student>();
File file =
new
File(filename);
FileReader fileReader =
null
;
BufferedReader bufferReader =
null
;
try
{
fileReader =
new
FileReader(file);
bufferReader =
new
BufferedReader(fileReader);
String line =
null
;
for
(
int
count =
0
; (line = bufferReader.readLine()) !=
null
; count++){
if
(count >= students.length){
throw
new
DataLoadException();
}
String[] contents =
new
String[
6
];
StringTokenizer stringTokenizer =
new
StringTokenizer(line);
for
(
int
i =
0
; stringTokenizer.hasMoreTokens(); i++){
contents[i] =
new
String(stringTokenizer.nextToken());
}
Student student =
new
Student(Integer.parseInt(contents[
0
]));
for
(
int
i =
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(
new
Student[studentList.size()]);
}
}
注:原文见我的博客《Java自定义异常处理》
0 0
- Java自定义异常处理
- java自定义异常处理
- Java异常处理-----自定义异常
- Java异常处理--自定义异常
- java异常处理之自定义异常类
- java异常处理之自定义异常类
- Java异常处理:Part3 自定义异常
- java例程练习(自定义异常处理)
- java面向对象-自定义异常处理
- Java用户自定义异常Exception处理
- 异常处理+异常+处理异常+自定义异常
- java异常处理之自定义异常类(转)
- 黑马程序员 Java基础 处理异常信息以及自定义异常
- 八、java的异常处理机制及自定义异常
- Java中自定义异常类_异常处理
- Java学习笔记之异常、处理异常、异常抛出、自定义异常、异常链
- VB自定义异常处理
- 自定义异常处理
- 剂朴伊缎锌倮图擅
- 剂朴伊缎锌倮图擅
- 剂朴伊缎锌倮图擅
- Statistical Analysis of fMRI Data- 2: Basic MR Physics
- UIWebView展示html富文本
- Java自定义异常处理
- UIWebView的基本用法
- Floyd判圈算法
- 学习笔记(objective-c)-扩展(extension)
- (9)命令模式
- (10)责任链模式
- (11)装饰模式
- PART2 敏捷测试象限
- nginx单机1W并发优化