写出10个【非检查】异常的代码实例
时间: 2024-10-24 08:13:24 浏览: 10
在Java中,非检查异常(也称为运行时异常或 unchecked exception)通常是由程序逻辑错误引起的,而不是由外部因素如文件不存在或网络连接失败等造成的。它们不需要在方法声明处捕获或抛出,但如果未处理,程序会终止。下面是10个常见的非检查异常及其简单的代码示例:
1. `NullPointerException` (空指针异常)
```java
public void method() {
String str = null;
System.out.println(str.length());
}
```
2. `ArrayIndexOutOfBoundsException` (数组越界异常)
```java
int[] array = {1, 2, 3};
System.out.println(array[5]);
```
3. `ArithmeticException` (算术异常,如除以零)
```java
double num = 0;
double result = 1 / num;
```
4. `IllegalArgumentException` (无效参数)
```java
String name = "";
List<String> names = new ArrayList<>();
names.add(name);
```
5. `FileNotFoundException` (虽然这是一个检查异常,但在此场景下可以忽略,因为它属于资源找不到的情况)
```java
File file = new File("non_existent_file.txt");
Scanner scanner = new Scanner(file);
```
6. `IOException` (输入/输出异常)
```java
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("file.txt"));
} catch (IOException e) {
// 捕获并处理异常
}
```
7. `ClassCastException` (类型转换异常)
```java
Object obj = "string";
Integer num = (Integer)obj; // 尝试将字符串转换为整数
```
8. `SQLException` (数据库操作异常)
```java
Connection conn = DriverManager.getConnection("...");
Statement stmt = conn.createStatement();
stmt.executeQuery("invalid query"); // 查询语法错误
```
9. `IllegalStateException` (状态异常)
```java
if (!lock.lock()) {
throw new IllegalStateException("Lock is already in use.");
}
```
10. `RuntimeException` (通用非检查异常,子类包括`NullPointerException`, `IllegalArgumentException`)
```java
throw new RuntimeException("A general runtime error occurred.");
```
阅读全文