Java异常处理

一、什么是异常
异常是指程序在执行过程中,由于程序的执行逻辑发生错误而发出的一种指令。
如下,执行处罚时产生的异常

public class Test1{
public static void main(String[]args){
System.out.println("请输入一个整数");
int a=10;
int b=0;
System.out.println("计算机结果是");
}
}

此异常是运算条件逻辑错误而出现的异常,此异常不解决,程序就会中断无法继续执行;

二、异常处理的两种方式

1、当场解决
try-catch

public void divide(int a,int b){
try{
int c=a/b;
System.out.println(c);
}catch(ArithmeticException e){
System.out.println("除数不能为零");
}
}
多个catch块(子类异常在前,父类在后)

try {
String s = null;
s.length();
} catch (NullPointerException e) {
System.out.println("空指针");
} catch (RuntimeException e) {
System.out.println("其他运行时异常");
}

finally常用来关闭资源

Scanner sc = null;
try {
sc = new Scanner(System.in);
int n = sc.nextInt();
} finally {
if (sc != null) sc.close();
}
2.throw(声明异常抛出)
语法:

import java.util.Scanner;
public class Test1{
public static void main(String[]args)throws ArithmeticException{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
TestMath math=new TestMath();
System.out,println("结果是:"+math.ma(10,n);
}
}
class TestMath{
public int ma(int a,int b)throws ArithmeticException{
int c=a/b;
return c;
}
}

注:当代码中出现不止一种异常,抛出异常就要按照可能出现的异常做抛出声明,可能出现的异常要与抛出的异常相匹配,声明多个抛出异常直接用(,)隔开。

三、二者的比对

try-catch在方法体内部,当场捕获并处理。可在当前方法内解决,或异常发生后使程序继续运行;
throw在方法名后,声明异常可能出现处,是当前方法不适合处理异常或让上层统一处理。

posted @ 2026-05-30 16:39  Znkunft  阅读(2)  评论(0)    收藏  举报