好吧...所以我正在學習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
在我看來,您需要閱讀有關已檢查和未經檢查的例外情況。 –