好吧...所以我正在学习java中的异常,我现在处于throw语句。我抛出Exception类的异常,然后再从catch块重新抛出它以在主函数中处理它。但是,每当我把它作为Exception类抛出时,我总是会在catch块中得到一个Error(在我重新抛出它的时候会被main处理)。但是,只要我将引发和捕获的异常更改为某些特定的异常(如NullPointerException)有用!从异常类中抛出异常在java中
错误代码:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(Exception e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new Exception("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(Exception e) {
System.out.println("Please handle the error");
throw e; // It gives me an error here
}
}
}
工作代码:
class ThrowingExceptions {
static boolean enable3dRendering = false;
public static void main(String [] com) {
try {
renderWorld();
}
catch(NullPointerException e) {
System.out.println("Rendering in 2d.");
}
}
static void renderWorld() {
try{
if(!enable3dRendering) {
System.out.println("3d rendering is disabled. Enable 3d mode to render.");
throw new NullPointerException("3d mode Disabled.");
}
else {
System.out.println("The World is Empty!");
}
}
catch(NullPointerException e) {
System.out.println("Please handle the error");
throw e;
}
}
}
为什么它不与Exception类的工作,并与它的子类的工作?
注: - 我在错误代码得到的错误是未处理的异常类型异常
当你在这里提出一个问题,请随时包括你所看到的到底是什么错误。 – nhouser9
在我看来,您需要阅读有关已检查和未经检查的例外情况。 –