Java异常处理
异常处理
-
异常处理的5个关键字
try catch语句用于捕获并处理异常
finally语句用于在任何情况下都必须执行的代码
throw语句用于抛出异常
throws语句用于声明可能会出现的异常
-
try-catch
public class Test03 { public static void main(String[] args) { Date date = readDate(); System.out.println("读取的日期 = " + date); } public static Date readDate() { FileInputStream readfile = null; InputStreamReader ir = null; BufferedReader in = null; try { //try块里声明的变量只在try块内有效 readfile = new FileInputStream("readme.txt"); ir = new InputStreamReader(readfile); in = new BufferedReader(ir); // 读取文件中的一行数据 String str = in.readLine(); if (str == null) { return null; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date date = df.parse(str); return date; //当一个catch块捕获到一个异常时,其他的catch块就不再进行匹配 } catch (FileNotFoundException e) { //是IOException的子类异常 System.out.println("处理FileNotFoundException..."); e.printStackTrace(); } catch (IOException e) { System.out.println("处理IOException..."); e.printStackTrace(); } catch (ParseException e) { System.out.println("处理ParseException..."); e.printStackTrace(); } return null; } /* 当捕获的多个异常类之间存在父子关系时,一般先捕获子类,所以子类异常必须在父类异常的前面,否则捕获不到 */ } -
try-catch-finally语句
无论是否有异常抛出,都会执行finally语句块中的语句
通常情况下,不在finally代码块中使用return或throw等导致方法终止的语句,否则将会导致try和catch代码块中的return和throw语句失效
-
声明异常throws和抛出异常throw
-
throws声明异常
当一个方法产生一个它不处理的异常时,就需要在方法的头部声明这个异常,以便将异常传递到方法的外部进行处理。使用throws声明的方法 表示此方法不处理异常
import java.io.FileInputStream; import java.io.IOException; public class Test04 { public void readFile() throws IOException { //将可能发生的异常交给调用者处理 // 定义方法时声明异常 FileInputStream file = new FileInputStream("read.txt"); // 创建 FileInputStream 实例对象 int f; while ((f = file.read()) != -1) { System.out.println((char) f); f = file.read(); } file.close(); } public static void main(String[] args) { Throws t = new Test04(); try { t.readFile(); // 调用 readFile()方法 } catch (IOException e) { // 捕获异常 System.out.println(e); } } }⚠️子类方法声明抛出的异常类型应该是父类方法声明抛出的异常类的子类或相同,子类方法声明抛出的异常不允许比父类方法声明抛出的异常多
-
throw抛出异常
throw语句用于直接抛出一个异常,后接一个可抛出的异常类对象
import java.util.Scanner; public class Test05 { public boolean validateUserName(String username) { boolean con = false; if (username.length() > 8) { // 判断用户名长度是否大于8位 for (int i = 0; i < username.length(); i++) { char ch = username.charAt(i); // 获取每一位字符 if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { con = true; } else { con = false; throw new IllegalArgumentException("用户名只能由字母和数字组成!"); } //当 throw 语句执行时,它后面的语句将不执行,此时程序转向调用者程序,寻找与之相匹配的 catch 语句,执行相应的异常处理程序。 } } else { throw new IllegalArgumentException("用户名长度必须大于 8 位!"); } return con; } public static void main(String[] args) { Test05 te = new Test05(); Scanner input = new Scanner(System.in); System.out.println("请输入用户名:"); String username = input.next(); try { boolean con = te.validateUserName(username); if (con) { System.out.println("用户名输入正确!"); } } catch (IllegalArgumentException e) { System.out.println(e); } } }
-

浙公网安备 33010602011771号