การจัดการข้อยกเว้นใน Java

⚡ สรุปอย่างชาญฉลาด

Java Exception Handling provides a structured mechanism to manage runtime errors that disrupt normal program flow. It uses try, catch, finally, throw, and throws keywords to detect, isolate, and recover from exceptional conditions while keeping applications robust and predictable.

  • ⚠️ Exception Defined: An exception is a runtime event that interrupts the standard execution sequence and is represented as an object describing the error condition.
  • 🧯 Try Catch Block: Wrap risky code inside a try block and follow it with one or more catch blocks to capture specific exception types gracefully.
  • 🔁 Finally Behavior: The finally block always executes after try and catch, making it ideal for closing files, sockets, or releasing other system resources.
  • Exception Hierarchy: All exceptions inherit from Throwable, which branches into Error and Exception, with RuntimeException covering unchecked cases such as divide by zero.
  • 🧪 ปฏิบัติที่ดีที่สุด: Catch the most specific exception first, avoid empty catch blocks, log meaningful messages, and use multi-catch to keep code concise and maintainable.

การจัดการข้อยกเว้นใน Java

What is an Exception in Java?

An ข้อยกเว้นใน Java is an event that interrupts the execution of program instructions and disturbs the normal flow of program execution. It is an object that wraps an error event information that occurred within a method, and it is passed to the runtime system. In Java, exceptions are mainly used to signal different types of error conditions so that developers can respond to them in a controlled way.

There are two broad categories of errors in Java:

  1. ข้อผิดพลาดในการคอมไพล์เวลา
  2. ข้อผิดพลาดรันไทม์

Compile time errors can be classified into two further types:

  • ข้อผิดพลาดทางไวยากรณ์
  • ข้อผิดพลาดทางความหมาย

ตัวอย่างข้อผิดพลาดทางไวยากรณ์:

แทนที่จะประกาศ. int a; คุณประกาศผิดว่าเป็น in a;, for which the compiler will throw an error.

Semantic Errors Example: You have declared a variable int a; และหลังจากโค้ดบางบรรทัด คุณจะประกาศจำนวนเต็มอีกครั้งเป็น int a;ข้อผิดพลาดทั้งหมดเหล่านี้จะถูกเน้นไว้เมื่อคุณคอมไพล์โค้ด

ตัวอย่างข้อผิดพลาดรันไทม์

A Runtime error is referred to as an ข้อยกเว้น. It is any event that interrupts the normal flow of program execution. Examples of exceptions include arithmetic exception, NullPointerException, divide by zero exception, and many more. Exceptions in Java are conditions that are often outside a developer’s direct control.

คลิก Good Farm Animal Welfare Awards หากไม่สามารถเข้าถึงวิดีโอได้

Why do we need Exception Handling?

Suppose you have coded a program to access a server. Things work fine while you are developing the code in a local environment with controlled conditions.

Java การจัดการข้อยกเว้น

During an actual production run, the server may be down. When your program tries to access it, an exception is raised, and without proper handling the program will terminate abruptly.

Java การจัดการข้อยกเว้น

How to Handle an Exception in Java

So far we have seen that an exception is often beyond a developer’s control. However, blaming code failure on environmental issues is not a real solution. You need robust programming that takes care of exceptional situations. Such code is known as an Exception Handler.

In our example, good exception handling would mean that when the primary server is down, the program automatically connects to a backup server.

Java การจัดการข้อยกเว้น

To implement this, you could write code to connect to the server using traditional if and else conditions. You will check if the server is down, and if yes, you will write code to connect to the backup server. Such organization of code using “if” and “else” branches is not effective when your code has multiple Java ข้อยกเว้น เพื่อจัดการ

class connect{
	if(Server Up){
	 // code to connect to server
	}
	else{
	 // code to connect to BACKUP server
	}
}

Try Catch Block in Java

Java provides an inbuilt exception handling mechanism that separates normal logic from error recovery logic.

  1. รหัสปกติจะเข้าสู่ a TRY กลุ่ม
  2. รหัสการจัดการข้อยกเว้นจะอยู่ในไฟล์ จับ กลุ่ม

ลองจับบล็อก

In our example, the TRY block will contain the code to connect to the server. The CATCH block will contain the code to connect to the backup server. In case the server is up, the code in the CATCH block will be ignored. In case the server is down, an exception is raised, and the code in the catch block will be executed.

ลองจับบล็อก

So, this is how an exception is handled in Java.

Syntax for using try and catch

try{
    statement(s)
}
catch (exceptiontype name){
	statement(s)
}

Example of Try Catch Block

ขั้นตอน 1) คัดลอกโค้ดต่อไปนี้ลงในโปรแกรมแก้ไข

class JavaException {
   public static void main(String args[]){
      int d = 0;
      int n = 20;
      int fraction = n/d;
     System.out.println("End Of Main");
   }
}

ขั้นตอน 2) Save the file and compile the code. Run the program using the command, java Javaข้อยกเว้น

ขั้นตอน 3) An Arithmetic Exception, divide by zero, is shown for line 5, and line 6 is never executed.

ขั้นตอน 4) Now let us examine how try and catch will help us to handle this exception. We will put the exception causing line of code into a ลอง บล็อกตามด้วย จับ บล็อก คัดลอกโค้ดต่อไปนี้ลงในตัวแก้ไข

class JavaException {
 public static void main(String args[]) {
  int d = 0;
  int n = 20;
  try {
   int fraction = n / d;
   System.out.println("This line will not be Executed");
  } catch (ArithmeticException e) {
   System.out.println("In the catch Block due to Exception = " + e);
  }
  System.out.println("End Of Main");
 }
}

ขั้นตอน 5) Save, compile, and run the code. You will get the following output.

ลองจับบล็อก

As you observe, the exception is handled, and the last line of code is also executed. Also, note that line 7 will not be executed because ทันทีที่มีข้อยกเว้นเกิดขึ้น การไหลของการควบคุมจะข้ามไปยังบล็อก catch

หมายเหตุ The ArithmeticException object “e” carries information about the exception that has occurred, which can be useful when taking recovery actions.

Java Exception Class Hierarchy

After one catch statement executes, the others are bypassed, and execution continues after the try and catch block. Nested catch blocks must follow the exception hierarchy from the most specific subclass to the most general parent class.

Java ลำดับชั้นข้อยกเว้น

  • คลาสข้อยกเว้นทั้งหมดใน Java extend the class Throwable. Throwable has two subclasses, Error and Exception.
  • The Error class defines the exceptions or problems that are not expected to occur under normal circumstances in your program, for example, memory error, hardware error, or JVM error.
  • The Exception class represents the exceptions that can be handled by your program, and your program can recover from these exceptions using try and catch blocks.
  • A RuntimeException is a subclass of the Exception class. Exceptions of this type represent unchecked exceptions that occur at runtime and cannot be detected at compile time. Good examples include divide by zero exception and null pointer exception.
  • IOException is generated during input and output operations.
  • InterruptedException in Java is generated during multithreaded operations when a thread is interrupted.

Example: Nesting of try and catch blocks

ขั้นตอน 1) คัดลอกโค้ดต่อไปนี้ลงในโปรแกรมแก้ไข

class JavaException {
 public static void main(String args[]) {
  try {
   int d = 1;
   int n = 20;
   int fraction = n / d;
   int g[] = {
    1
   };
   g[20] = 100;
  }
  /*catch(Exception e){
  	System.out.println("In the catch block due to Exception = "+e);
  }*/
  catch (ArithmeticException e) {
   System.out.println("In the catch block due to Exception = " + e);
  } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println("In the catch block due to Exception = " + e);
  }
  System.out.println("End Of Main");
 }
}

ขั้นตอน 2) Save the file and compile the code. Run the program using the command, ชวา Javaข้อยกเว้น.

ขั้นตอน 3) An ArrayIndexOutOfBoundsException is generated. Change the value of int d to 0. Save, compile, and run the code.

ขั้นตอน 4) An ArithmeticException must be generated.

ขั้นตอน 5) Uncomment line 10 to line 12. Save, compile, and run the code.

Step 6) Compilation Error? This is because Exception is the base class of ArithmeticException. Any exception that is raised by ArithmeticException can also be handled by the Exception class. So the catch block of ArithmeticException will never get a chance to execute, which makes it redundant. Hence the compilation error.

Java ในที่สุดก็บล็อค

บล็อกสุดท้ายก็คือ ดำเนินการโดยไม่คำนึงถึงข้อยกเว้นที่เกิดขึ้น ในบล็อกลอง มันคือ ไม่จำเป็น to use with a try block. The finally block is the right place to release resources such as database connections, files, or network sockets.

 try {
  statement(s)
 } catch (ExceptiontType name) {

  statement(s)

 } finally {

  statement(s)

 }

If an exception is raised in the try block, the finally block is executed after the catch block completes.

Example of finally Block

ขั้นตอน 1) คัดลอกโค้ดต่อไปนี้ลงในโปรแกรมแก้ไข

class JavaException {
   public static void main(String args[]){
    try{
       int d = 0;
       int n =20;
       int fraction = n/d;
    }
  catch(ArithmeticException e){
    System.out.println("In the catch block due to Exception = "+e);
  }
  finally{
	System.out.println("Inside the finally block");
  }
}
}

ขั้นตอน 2) บันทึก คอมไพล์ และรันโค้ด

ขั้นตอน 3) Expected output: The finally block is executed even though an exception is raised.

ขั้นตอน 4) Change the value of variable d = 1. Save, compile, and run the code, and observe the output.

แนวทางปฏิบัติที่ดีที่สุดสำหรับ Java การจัดการข้อยกเว้น

Following a few proven rules will help you keep your Java code resilient, readable, and easy to debug:

  • Catch the most specific exception first, then the more general ones, to preserve the integrity of the exception hierarchy.
  • Avoid empty catch blocks. At a minimum, log the exception so the root cause is never lost.
  • Use the finally block or try with resources to release files, sockets, and database connections.
  • Throw checked exceptions only when the caller can reasonably recover, and use unchecked exceptions for programming errors.
  • Wrap low level exceptions in a meaningful business exception to keep API contracts clean.
  • Never swallow InterruptedException silently in multithreaded code, restore the interrupt flag instead.

คำถามที่พบบ่อย

Checked exceptions are verified at compile time and must be declared or caught, such as IOException. Unchecked exceptions extend RuntimeException, occur at runtime, and do not require mandatory handling, such as NullPointerException or ArithmeticException.

The finally block always runs after the try and catch blocks, whether an exception occurred or not. It is the safest place to release resources such as file handles, database connections, or sockets, ensuring clean termination of operations.

The throw keyword is used inside a method to actually raise an exception object, while throws is used in a method signature to declare that the method may pass certain checked exceptions to its caller for handling.

Yes. A try block can be followed by a finally block without any catch block. This pattern is used when the developer wants to ensure cleanup code executes even though the exception itself is propagated to the caller.

Yes. AI powered observability tools analyze stack traces, logs, and code paths to predict where runtime exceptions are likely to occur. They suggest defensive checks, recommend catch placement, and surface anomalies, helping teams prevent crashes before they reach production.

AI assistants parse stack traces, correlate them with source code, and suggest probable root causes plus fixes. They generate try catch templates, recommend logging improvements, and even rewrite faulty methods, dramatically reducing the time developers spend diagnosing Java ข้อยกเว้น

สรุปโพสต์นี้ด้วย: