3月9号总结
1. 内置异常方法
方法 说明
public String getMessage() 返回关于发生的异常的详细信息。这个消息在Throwable 类的构造函数中初始化了。
public Throwable getCause() 返回一个 Throwable 对象代表异常原因。
public String toString() 返回此 Throwable 的简短描述。
public void printStackTrace() 将此 Throwable 及其回溯打印到标准错误流
public StackTraceElement [] getStackTrace() 返回一个包含堆栈层次的数组。下标为0的元素代表栈顶,最后一个元素代表方法调用堆栈的栈底。
public Throwable fillInStackTrace() 用当前的调用栈层次填充Throwable 对象栈层次,添加到栈层次任何先前信息中。
2.捕捉异常
import java.util.Scanner; public class Main { private static void foo() { int[] array = new int[5]; for (int i = 0; i < 5; i ++ ) array[i] = i; Scanner sc = new Scanner(System.in); int k = sc.nextInt(); int x = sc.nextInt(); try { array[k] /= x; } catch (ArithmeticException e) { System.out.println("除零错误!"); e.printStackTrace(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("数组越界!"); e.printStackTrace(); } finally { for (int i = 0; i < 5; i ++ ) { System.out.println(array[i]); } } } public static void main(String[] args) { foo(); } }
3. 抛出异常
throw: 在函数内抛出一个异常。
throws:在函数定义时抛出一些可能的异常。
检查型异常必须被捕获或者抛出。
import java.io.IOException; import java.util.Scanner; public class Main { private static void foo() throws IOException, NoSuchFieldException { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); if (x == 1) throw new IOException("找不到文件!!!"); else throw new NoSuchFieldException("自定义异常"); } public static void main(String[] args) { try { foo(); } catch (IOException e) { System.out.println("IOException!"); e.printStackTrace(); } catch (NoSuchFieldException e) { System.out.println("NoSuchFieldException!"); e.printStackTrace(); } } }
8. try-with-resources
JDK7 之后,Java 新增的 try-with-resource 语法糖来打开资源,并且可以在语句执行完毕后确保每个资源都被自动关闭 。
try 用于声明和实例化资源,catch 用于处理关闭资源时可能引发的所有异常。
import java.io.*; public class Main { public static void main(String[] args) { String line; try ( BufferedReader br = new BufferedReader(new FileReader("input.txt")); BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); ) { while ((line = br.readLine()) != null) { System.out.println("Line => " + line); bw.write("copy: " + line + "\n"); } bw.flush(); } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具