1.Exception(异常)
- 异常分为编译时异常和运行时异常
- 对于编译异常,程序必须处理
- 对于运行时异常,程序中如果没有处理,默认就是throws
1.1 try-catch
try{ //代码 }catch (Exception e){ //try代码发生异常catch执行 //可以有多个catch分别捕获不同异常相应处理,子类异常在前,父类异常在后 }finally { //不管try发不发生异常,finally中的代码都会执行 //没有finally是允许的 //可以try-finally,没有catch,发生异常程序会直接throw }
- 没有try-catch默认throws
- 一个实例:输入的如果不是整数就反复提醒输入
package exception_;import java.util.Scanner;public class Exception01 { public static void main(String[] args) { int num = 0; Scanner scanner = new Scanner(System.in); String input = ""; while (true){ input = scanner.next(); try { num = Integer.parseInt(input); break; } catch (NumberFormatException e) { System.out.println("你输入的不是整数"); } } System.out.println("你输入的是" + num); }}
1.2 throws
- 不对异常进行处理,而抛给调用者进行处理
这里的FileNotFoundException是编译时异常,因为没有文件d://aa.txt,程序会报错,但是把异常抛出后程序不会报错,异常会抛给调用f1的函数处理。
package exception_;import java.io.FileInputStream;import java.io.FileNotFoundException;public class Exception02 { void f1() throws FileNotFoundException{ FileInputStream file = new FileInputStream("d://aa.txt"); }}
package exception_;public class CustomException { public static void main(String[] args) { int age= 120; if(!(age >= 18 && age <=70 )){ throw new AgeException("年龄要在18~70之间"); } System.out.println("年龄正确"); }}//自定义一个异常class AgeException extends RuntimeException { public AgeException(String message) { super(message); }}