在Java中,所有的异常都是java.lang.Throwable类的子类。Throwable类有两个主要的子类:java.lang.Error和java.lang.Exception。
接下来,我将通过几个示例程序来演示Java中异常的发生和处理。
import java.io.FileInputStream;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("nonexistent.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在上面的例子中,我们尝试打开一个不存在的文件,这会抛出FileNotFoundException,它是IOException的一个子类,属于已检查异常。我们使用try-catch块来捕获并处理这个异常。
public class UncheckedExceptionExample {
public static void main(String[] args) {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们尝试做一个除以零的操作,这会抛出ArithmeticException,属于未检查异常。我们同样使用try-catch块来处理这个异常。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception.");
} catch (CustomException e) {
e.printStackTrace();
}
}
}
在这个例子中,我们定义了一个名为CustomException的自定义异常,并在main方法中抛出它。我们使用try-catch块来捕获并处理这个自定义异常。
处理异常的方式主要有两种:
通过上面的示例程序和解释,你应该对Java中的异常和如何处理它们有了基本的了解。在实际编程中,合理地使用异常处理机制是提高代码健壮性和可维护性的关键。
上一篇:今天来聊聊-身份问题!
下一篇:分库分表设计及常见问题