Java异常处理机制与常见异常示例
Java异常处理机制是Java语言中用于处理程序运行时错误的一种机制。它允许程序在发生异常时不直接崩溃,而是能够捕获异常并进行相应的处理。Java异常处理主要涉及以下几个关键概念:
- 异常(Exception):程序运行时发生的非正常情况,导致程序不能继续正常执行。
- 错误(Error):程序运行时发生的严重问题,通常是由JVM抛出的,比如
OutOfMemoryError
。 - 检查型异常(Checked Exception):必须被程序显式处理的异常,编译器会检查是否对这些异常进行了处理。
- 非检查型异常(Unchecked Exception):不需要程序显式处理的异常,通常是
RuntimeException
的子类。 - 异常处理关键字:
try
:用于包裹可能发生异常的代码块。catch
:用于捕获并处理try
块中发生的异常。finally
:无论是否发生异常,finally
块中的代码都会被执行,常用于资源清理。throw
:用于手动抛出异常。throws
:用于声明方法可能抛出的异常。
常见异常示例以下是一些Java中常见的异常及其简要说明:
NullPointerException
:尝试使用null
对象的实例方法或字段时抛出。javaObject obj = null; obj.toString(); //抛出NullPointerException
2.ArithmeticException
:算术运算异常,比如除以零。javaint a =10; int b =0; int result = a / b; //抛出ArithmeticException
3.ArrayIndexOutOfBoundsException
:数组索引越界。javaint[] array = new int[5]; array[5] =10; //抛出ArrayIndexOutOfBoundsException
4.ClassCastException
:类型转换异常,尝试将对象强制转换为不兼容的类型。javaObject obj = "Hello"; String str = (String) obj; //正常Integer num = (Integer) obj; //抛出ClassCastException
5.IOException
:输入输出异常,通常在文件操作中遇到。java try (FileWriter writer = new FileWriter("file.txt")) { writer.write("Hello"); } catch (IOException e) { e.printStackTrace(); }
6.SQLException
:数据库操作异常。javaConnection conn = DriverManager.getConnection(url, user, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM non_existent_table"); //抛出SQLException
7.IllegalArgumentException
:非法参数异常,方法接收到不合法的参数时抛出。java public void printArray(int[] array) { if (array == null) { throw new IllegalArgumentException("Array cannot be null"); } }
8.NumberFormatException
:数字格式异常,尝试将字符串转换为数字时,字符串格式不正确。javaInteger.parseInt("abc"); //抛出NumberFormatException
通过合理使用异常处理机制,可以提高程序的健壮性和用户体验。
还没有评论,来说两句吧...