搜索
写经验 领红包
 > 时尚

程序中的异常是什么(程序出现异常会执行哪个语句)

导语:程序员必备:异常的十个关键知识点

一. 异常是什么

异常是指阻止当前方法或作用域继续执行的问题。比如你读取的文件不存在,数组越界,进行除法时,除数为0等都会导致异常。

一个文件找不到的异常:

运行结果:

Exception in thread &34; java.io.FileNotFoundException: jaywei.txt (系统找不到指定的文件。)

at java.io.FileInputStream.open0(Native Method)

at java.io.FileInputStream.open(FileInputStream.java:195)

at java.io.FileInputStream.<init>(FileInputStream.java:138)

at java.io.FileInputStream.<init>(FileInputStream.java:93)

at exception.TestException.main(TestException.java:10)

二. 异常的层次结构

Error

表示编译时或者系统错误,如虚拟机相关的错误,OutOfMemoryError等,error是无法处理的。

Exception

代码异常,Java程序员关心的基类型通常是Exception。它能被程序本身可以处理,这也是它跟Error的区别。

它可以分为RuntimeException(运行时异常)和CheckedException(可检查的异常)。

常见的RuntimeException异常:

- NullPointerException 空指针异常

- ArithmeticException 出现异常的运算条件时,抛出此异常

- IndexOutOfBoundsException 数组索引越界异常

- ClassNotFoundException 找不到类异常

- IllegalArgumentException(非法参数异常)

常见的 Checked Exception 异常:

- IOException (操作输入流和输出流时可能出现的异常)

- ClassCastException(类型转换异常类)

Checked Exception就是编译器要求你必须处置的异常。与之相反的是,Unchecked Exceptions,它指编译器不要求强制处置的异常,它包括Error和RuntimeException 以及他们的子类。

三、异常处理

当异常出现后,会在堆上创建异常对象。当前的执行路径被终止,并且从当前环境中弹出对异常对象的引用。这时候异常处理程序,使程序从错误状态恢复,使程序继续运行下去。

异常处理主要有抛出异常、捕获异常、声明异常。如图:

捕获异常

try{

// 程序代码

}catch(Exception e){

//Catch 块

}finaly{

//无论如何,都会执行的代码块

}

声明抛出异常

//该方法通过throws声明了IO异常。

private void readFile() throws IOException {

InputStream is = new FileInputStream(&34;);

int b;

while ((b = is.read()) != -1) {

}

}

抛出异常

throw关键字作用是抛出一个 Throwable类型的异常,它一般出现在函数体中。在异常处理中,try语句要捕获的是一个异常对象,其实此异常对象也可以自己抛出。

例如抛出一个 RuntimeException 类的异常对象:

throw new RuntimeException(e);

任何Java代码都可以通过 Java 的throw语句抛出异常

Java异常类的几个重要方法

getMessage

Returns the detail message string of this throwable.

getMessage会返回Throwable的 detailMessage属性,而 detailMessage就表示发生异常的详细消息描述。

举个例子, FileNotFoundException异常发生时,这个 detailMessage就包含这个找不到文件的名字。

getLocalizedMessage

Creates a localized description of this throwable.Subclasses may override this

method in order to produce alocale-specific message. For subclasses that do not

override thismethod, the default implementation returns the same result

as getMessage()

throwable的本地化描述。子类可以重写此方法,以生成特定于语言环境的消息。对于不覆盖此方法的子类,默认实现返回与相同的结果 getMessage()。

getCause

Returns the cause of this throwable or null if thecause is nonexistent or unknown.

返回此可抛出事件的原因,或者,如果原因不存在或未知,返回null。

printStackTrace

Prints this throwable and its backtrace to thestandard error stream.

The first line of output contains the result of the toString() method for

this object.Remaining lines represent data previously recorded by the

method fillInStackTrace().

该方法将堆栈跟踪信息打印到标准错误流。

输出的第一行,包含此对象toString()方法的结果。剩余的行表示,先前被方法fillInStackTrace()记录的数据。如下例子:

java.lang.NullPointerException

at MyClass.mash(MyClass.java:9)

at MyClass.crunch(MyClass.java:6)

at MyClass.main(MyClass.java:3)

本文内容由小樊整理编辑!