- 输入会出错
- 设备会出错
- 存储会出错
- 代码错误
1 异常分类
运行时异常
- 一个失败的强制类型转换
- 数组超出异常
- 空指针异常
- …
其他不是运行时异常
- 试图在文件尾部读取数据
- 试图打开不存在的文件
- 试图从给定字符串寻找类,而这个类不存在
一旦有运行时异常,那是我们的错,程序没写好。
错误和运行时异常属于未检查异常,其他异常成为已检查异常。
2 声明已检查异常
对于可能出现异常的部位要对异常进行检测。
public FileInputStream(String name) throws FileNotFoundException
例如,这个FileInputStream类,如果正确运行,则用name新建了一个FileInputStream对象,如果出现异常则不会创建对象而是抛出FileNotFoundException异常。
下面情况应该抛出异常:
- 调用一个会抛出已检查异常的方法
- 程序运行过程中发现错误
- 程序出现错误
- Java虚拟机和运行时库出现内部错误
class MyAnimation
{
...
//一个方法可以抛出多个可能的异常
public Image loadImage(String s) throws FileNotFoundException, EOFException
{
...
}
}
3 如何抛出异常
String readData(Scanner in) throws EOFException
{
. . .
while (. . .)
{
if (!in.hasNext()) // EOF encountered
{
if (n < len)
{
String gripe = "Content-length: " + len + ", Received: " + n;
throw new EOFException(gripe);
}
}
. . .
}
return s;
}
- 找到合适的异常类
- 创建这个类的对象
- 抛出这个异常
注意:一旦决定抛出异常后,就不用考虑这个方法的返回值问题了,因为,方法都没有运行成功,要什么结果。
4 创建异常类
class FileFormatException extends IOException
{
public FileFormatException() {}
public FileFormatException(String gripe)
{
super(gripe);
}
}
String readData(BufferedReader in) throws FileFormatException
{
. . .
while (. . .)
{
if (ch == -1) // EOF encountered
{
if (n < len)
throw new FileFormatException();
}
. . .
}
return s;
}
本文详细介绍了Java中的异常处理机制,包括运行时异常与已检查异常的区别,如何声明与抛出异常,以及如何创建自定义异常类等内容。
1492

被折叠的 条评论
为什么被折叠?



