自学内容网 自学内容网

Java中的异常类型

在Java中,异常分为两大类:受检异常(Checked Exceptions)和非受检异常(Unchecked Exceptions)。受检异常需要在代码中显式地处理(例如通过try-catch块),而非受检异常可以不显式处理。以下是一些常见的Java异常类型:

1. 受检异常(Checked Exceptions)

IOException
  • 描述:发生I/O操作错误时抛出,如文件读写失败。
  • 示例:
    import java.io.*;
    
    public class Main {
        public static void main(String[] args) {
            try {
                FileInputStream file = new FileInputStream("test.txt");
            } catch (IOException e) {
                System.out.println("Caught IOException: " + e.getMessage());
            }
        }
    }
    
SQLException
  • 描述:在与数据库交互时发生错误时抛出。
  • 示例:
    import java.sql.*;
    
    public class Main {
        public static void main(String[] args) {
            try {
                Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
            } catch (SQLException e) {
                System.out.println("Caught SQLException: " + e.getMessage());
            }
        }
    }
    
ClassNotFoundException
  • 描述:在尝试加载类时找不到类时抛出。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            try {
                Class.forName("com.example.MyClass");
            } catch (ClassNotFoundException e) {
                System.out.println("Caught ClassNotFoundException: " + e.getMessage());
            }
        }
    }
    

2. 非受检异常(Unchecked Exceptions)

NullPointerException
  • 描述:在应用程序试图使用null对象引用时抛出。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            String str = null;
            try {
                System.out.println(str.length());
            } catch (NullPointerException e) {
                System.out.println("Caught NullPointerException: " + e.getMessage());
            }
        }
    }
    
ArrayIndexOutOfBoundsException
  • 描述:当数组下标越界时抛出。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            int[] arr = {1, 2, 3};
            try {
                System.out.println(arr[3]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
            }
        }
    }
    
ArithmeticException
  • 描述:当数学运算中发生错误时抛出,例如除以零。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            try {
                int result = 10 / 0;
            } catch (ArithmeticException e) {
                System.out.println("Caught ArithmeticException: " + e.getMessage());
            }
        }
    }
    
IllegalArgumentException
  • 描述:当传递给方法的参数非法或不合适时抛出。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            try {
                Thread.sleep(-1);
            } catch (IllegalArgumentException e) {
                System.out.println("Caught IllegalArgumentException: " + e.getMessage());
            } catch (InterruptedException e) {
                System.out.println("Caught InterruptedException: " + e.getMessage());
            }
        }
    }
    
NumberFormatException
  • 描述:当尝试将字符串转换为数值类型但失败时抛出。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            try {
                int num = Integer.parseInt("abc");
            } catch (NumberFormatException e) {
                System.out.println("Caught NumberFormatException: " + e.getMessage());
            }
        }
    }
    

总结

Java中有许多常见的异常类型,每种异常类型都有其特定的使用场景和解决方法。了解和正确处理这些异常,有助于编写健壮和可靠的Java代码。

当然,Java中还有很多其他异常类型。下面列出一些其他常见的异常类型,并介绍如何创建自定义异常。

其他常见异常类型

IndexOutOfBoundsException
  • 描述:用于指示某种类型的索引超出范围的情况。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            try {
                ArrayList<Integer> list = new ArrayList<>();
                list.add(1);
                System.out.println(list.get(2));
            } catch (IndexOutOfBoundsException e) {
                System.out.println("Caught IndexOutOfBoundsException: " + e.getMessage());
            }
        }
    }
    
ClassCastException
  • 描述:当试图将对象强制转换为不是实例的子类时抛出。
  • 示例:
    public class Main {
        public static void main(String[] args) {
            try {
                Object obj = new Integer(100);
                String str = (String) obj;
            } catch (ClassCastException e) {
                System.out.println("Caught ClassCastException: " + e.getMessage());
            }
        }
    }
    
IllegalStateException
  • 描述:当方法调用的状态不合法或不适合时抛出。
  • 示例:
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            try {
                ArrayList<Integer> list = new ArrayList<>();
                Iterator<Integer> iterator = list.iterator();
                iterator.remove();
            } catch (IllegalStateException e) {
                System.out.println("Caught IllegalStateException: " + e.getMessage());
            }
        }
    }
    
UnsupportedOperationException
  • 描述:当不支持请求的操作时抛出。
  • 示例:
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            try {
                List<String> list = Arrays.asList("one", "two", "three");
                list.add("four");
            } catch (UnsupportedOperationException e) {
                System.out.println("Caught UnsupportedOperationException: " + e.getMessage());
            }
        }
    }
    

自定义异常

在Java中,你可以创建自定义异常类来表示特定的异常情况。自定义异常通常继承自Exception类 或RuntimeException类。以下是如何创建和使用自定义异常的示例。

创建自定义异常
  1. 继承Exception:用于受检异常。
  2. 继承RuntimeException:用于非受检异常。
示例1:继承Exception
class MyCustomException extends Exception {
    public MyCustomException(String message) {
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            testMethod(0);
        } catch (MyCustomException e) {
            System.out.println("Caught MyCustomException: " + e.getMessage());
        }
    }

    public static void testMethod(int value) throws MyCustomException {
        if (value == 0) {
            throw new MyCustomException("Value cannot be zero.");
        }
    }
}
示例2:继承RuntimeException
class MyCustomRuntimeException extends RuntimeException {
    public MyCustomRuntimeException(String message) {
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        try {
            testMethod(0);
        } catch (MyCustomRuntimeException e) {
            System.out.println("Caught MyCustomRuntimeException: " + e.getMessage());
        }
    }

    public static void testMethod(int value) {
        if (value == 0) {
            throw new MyCustomRuntimeException("Value cannot be zero.");
        }
    }
}

总结

除了常见的异常类型外,Java还允许你创建自定义异常来处理特定的错误情况。通过继承ExceptionRuntimeException类,你可以定义自己的异常类型,并在适当的时候抛出这些异常,从而使代码更加健壮和易于维护。


原文地址:https://blog.csdn.net/ozawacai/article/details/140266120

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!