异常
异常:指出程勋的Bug
继承结构
Throwable
--Error:一般不是软件问题
--Exception
XXXXXException 全是Exception的子类
异常处理
--捕获:有异常,自己处理,并提供处理方法,别人调用很安全
try{
有问题的代码
}catch(异常类型1 异常名){
给出处理方案1
}catch(异常类型2 异常名){
给出处理方案2
}
--抛出:有异常,自己不处理,谁调用谁去处理
在方法声明上 加 throws 异常类型1,异常类型2.。。。
import java.util.InputMismatchException;
import java.util.Scanner;
//异常
public class C3 {
public static void main(String[] args){
//method();
//捕获 抛出的异常
try {
method1();// 抛出异常---调用了一个有异常的方法,得进行异常的处理--抛出/捕获
}catch(Exception e){
System.out.println("执行失败");
}
}
//捕获异常
public static void method() {
try {
//1.接受2个整数
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
//除法运算
System.out.println(a / b);
}catch (InputMismatchException a) {
System.out.println("请输入整数");
} catch (ArithmeticException b) {
System.out.println("第二次请不要输入0");
}//问题:还有其他异常
//不关心具体的类型
//多态
catch (Exception c){
// 还想捕获其它的,所有的异常,但是不知道还有几个,都叫啥,怎么办?
// 多态,不管子类具体叫什么,都把子类当父类来看,更通用 !!
System.out.println("输入有问题");
}catch(Exception e) {
//开发调试阶段用e -- 给程序员用 , 跟踪错误的
e.printStackTrace();
//把错误已经处理了 -- 项目上线用 , 让用户看的
System.out.println("运行错误!");
}finally {// 最终的,,,,,,通常放,必须要执行的代码
//放非得执行的 -- 比如: 释放资源
System.out.println(3);
System.out.println(4);
}
}
//抛出异常 谁调用。谁处理 ---throws 不提倡
public static void method1()throws Exception{
//1.接受2个整数
int a = new Scanner(System.in).nextInt();
int b = new Scanner(System.in).nextInt();
System.out.println(a/b);
}
}
浙公网安备 33010602011771号