คุณสมบัติ Exception Handling มีในภาษา object-oriented เกือบทุกภาษา รวมถึง C++ และ Java มีความคล้ายคลึงกัน เช่น ทั้งคู่ใช้ try-catch block แต่ก็มีความแตกต่าง:
ใน C++ สามารถ throw ข้อมูลประเภทไหนก็ได้: primitive types และ pointers ใน Java throw ได้เฉพาะ throwable objects (subclass ของ Throwable)
ตัวอย่าง C++: throw int
#include <iostream>
using namespace std;
int main() {
int x = -5;
try {
if (x < 0) throw x;
} catch (int x) {
cout << "Exception Caught: thrown value is " << x << endl;
}
}
ผลลัพธ์
Exception Caught: thrown value is -5
ใน C++ มี catch-all เพื่อจับ exception ทุกประเภท:
try { ... } catch(...) { ... }
ตัวอย่าง C++: catch-all
#include <iostream>
using namespace std;
int main() {
int x = -5;
char y = 'A';
try {
if (x < 0) throw x;
if (y == 'A') throw y;
} catch (...) {
cout << "Exception Caught" << endl;
}
}
ผลลัพธ์
Exception Caught
ใน Java ถ้าจับทุกประเภท ใช้ Exception class (superclass ของทุก exception):
try { ... } catch (Exception e) { ... }
C++ ไม่มี finally block แต่ Java มี finally block โค้ดใน finally จะรันทุกครั้ง ไม่ว่าจะมี exception หรือไม่
ตัวอย่าง Java: finally
public class HelloWorld {
public static void main(String[] args) {
try {
int data = 25/5;
System.out.println(data);
} catch (NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
ผลลัพธ์
5 finally block is always executed rest of the code...