一. 异常体系结构
二.异常处理机制
1.捕获异常:try,catch,finally
package com.microsoft.bean;
public class Test {
public static void main(String[] args) {
int one = 1;
int two = 0;
// try表示监控区域
try {
// 监控对象
System.out.println(one/two);
// catch表示捕获异常,()Exception内表示异常类型,e表示异常对象
} catch (Exception e) {
// 捕获成功后,输出语句
System.out.println("程序出现异常,变量two不能为0");
// finally表示善后工作,可以不写,因为默认存在。
// 但在一些情况中,必须写,如io流,资源,等等
} finally {
System.out.println("善后工作");
}
}
}
例子2:错误
package com.microsoft.bean;
public class Test {
public static void main(String[] args) {
// 这段代码可以理解为创建了一个 Test 类的对象,并调用了该对象的 one() 方法。
// 具体来说,new Test() 创建了一个 Test 类的匿名对象,并通过该对象调用了 one() 方法。
// 这种方式常用于一次性调用某个类的方法而不需要保留对象的引用。
new Test().one();
}
public void one(){
two();
}
public void two(){
one();
}
}
package com.microsoft.bean;
public class Test {
public static void main(String[] args) {
try {
new Test().one();
// 此时的异常类型应该是错误
} catch (Error e) {
System.out.println("虚拟机出现错误");
} finally {
System.out.println("善后工作");
}
}
public void one(){
two();
}
public void two(){
one();
}
}
如果不知道异常类型可以使用多层捕获,但括号中的捕获类型必须从小到大,捕获类型大小见第一张图;
package com.microsoft.bean;
public class Test {
public static void main(String[] args) {
try {
new Test().one();
} catch (Exception e) {
System.out.println("Exception");
} catch (Error e) {
System.out.println("Error");
} catch (Throwable e) {
System.out.println("Throwable");
}finally {
System.out.println("善后工作");
}
}
public void one(){
two();
}
public void two(){
one();
}
}
2.抛出异常: throw,throws,一般在方法中使用
package com.microsoft.bean;
import com.sun.org.apache.xerces.internal.impl.dv.xs.YearDV;
public class Test {
public static void main(String[] args) {
new Test().test(3, 0);
}
public void test(int one, int two){
if(two == 0){
// two等于0,就抛出异常
throw new ArithmeticException();
}
}
}
package com.microsoft.bean;
import com.sun.org.apache.xerces.internal.impl.dv.xs.YearDV;
public class Test {
public static void main(String[] args) {
new Test().test(3, 0);
}
// 如果方法中,处理不了这个异常,那就方法上抛出异常
public void test(int one, int two) throws ArithmeticException{
if(two == 0){
// two等于0,就抛出异常
throw new ArithmeticException();
}
}
}
三.自定义异常
package com.microsoft.bean;
class One extends Exception{
// 我们使用构造函数,并在其中调用了父类Exception的构造函数来设置异常消息。
public One() {
super("输入的数字不能为负数");
}
}
public class Test {
public static void main(String[] args) {
int number = -5;
try {
// 监控区域,判断是否输出数字是否非负数
// 如果是抛出,到下面的捕获异常
if (number < 0) {
throw new One();
}
// 如果不是,则输出输入的数字
System.out.println("输入的数字是:" + number);
// 捕获异常类型为自定义One
} catch (One e) {
// 如果上面抛出的异常,是负数,这打印错误栈的信息
System.out.println(e.getMessage());
}
}
}