"ฉันอยากจะบอกคุณสักเล็กน้อยเกี่ยวกับวิธี การทำงาน ของข้อยกเว้นตัวอย่างด้านล่างควรให้แนวคิดคร่าวๆ แก่คุณเกี่ยวกับสิ่งที่เกิดขึ้น:"
class ExceptionExampleOriginal
{
public static void main(String[] args)
{
System.out.println("main begin");
try
{
System.out.println("main before call");
method1();
System.out.println("main after call");
}
catch (RuntimeException e)
{
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
throw new RuntimeException(s);
}
}
public class ExceptionExample
{
private static Exception exception = null;
public static void main(String[] args)
{
System.out.println("main begin");
System.out.println("main before call");
method1();
if (exception == null)
{
System.out.println("main after call");
}
else if (exception instanceof RuntimeException)
{
RuntimeException e = (RuntimeException) exception;
exception = null;
String s = e.getMessage();
System.out.println(s);
}
System.out.println("main end");
}
public static void method1()
{
System.out.println("method1 begin");
method2();
if (exception != null) return;
System.out.println("method1 end");
}
public static void method2()
{
System.out.println("method2");
String s = "Message: Unknown Exception";
exception = new RuntimeException(s);
return;
}
}
"ฉันหลงทางไปหมดแล้ว"
“เอาล่ะ ฉันจะอธิบายสิ่งที่เกิดขึ้น”
"ในตัวอย่างด้านซ้าย เราเรียกใช้เมธอดสองสามวิธีติดต่อกัน ในmethod2
เราจงใจสร้างและโยนข้อยกเว้น (เราสร้างข้อผิดพลาด)"
"ตัวอย่างด้านขวาแสดงให้เห็นว่าเกิดอะไรขึ้น"
"ดูที่method2
แทนที่จะสร้างข้อยกเว้น เราสร้างวัตถุRuntimeException
บันทึกลงในตัวแปรสแตติกexception
แล้วออกจากเมธอดทันทีโดยใช้return
คำสั่ง"
"ในmethod1
หลังจากการเรียกmethod2
เราจะตรวจสอบว่ามีข้อยกเว้นหรือไม่ หากมีข้อยกเว้นmethod1
ให้สิ้นสุดทันทีการตรวจสอบเช่นนี้จะดำเนินการทางอ้อมหลังจากการเรียกเมธอด (!) ทุกครั้งใน Java"
"ว้าว!"
"ว้าว ถูกต้องครับ"
"ในคอลัมน์ด้านขวา ฉันได้ใช้วิธีหลักเพื่อแสดงโดยประมาณว่าเกิดอะไรขึ้นเมื่อตรวจพบข้อยกเว้นโดยใช้โครงสร้าง try-catch หากไม่มีข้อยกเว้น ทุกอย่างจะทำงานต่อไปตามที่คาดไว้ หากมีข้อยกเว้นและ เป็นประเภทเดียวกับที่ระบุในคำสั่ง catch แล้วเราจะจัดการให้"
"ทำอะไร throw
และ instanceof
หมายความว่าอย่างไร "
"ดูที่บรรทัดสุดท้าย: throw new RuntimeException(s);
นี่คือวิธีที่คุณสร้างและโยนข้อยกเว้น เรายังดำเนินการไม่ได้ มันเป็นเพียงตัวอย่างเท่านั้น"
"เราใช้a instanceof B
เพื่อตรวจสอบว่าวัตถุa
เป็นประเภทB
หรือไม่ กล่าวคือวัตถุที่อ้างอิงโดยข้อยกเว้นตัวแปรนั้นเป็น RuntimeException หรือไม่ นี่เป็นนิพจน์บูลีน"
"ฉันคิดว่าฉันเข้าใจแล้ว เกือบแล้ว"
GO TO FULL VERSION