Java 7: Cách bắt nhiều ngoại lệ trong cùng một catch block
2 phút đọc30/08/2025
Bao Tran
Web Developer
0 lượt xem
0 lượt xem
Reading Time: 2minutes
Trong Java 7, catch block đã được cải tiến để xử lý nhiều exception trong một catch block duy nhất. Nếu bạn đang bắt nhiều exception và chúng có đoạn code xử lý tương tự nhau, thì việc sử dụng tính năng này sẽ giúp giảm trùng lặp code.
Hãy cùng tìm hiểu tính năng bắt nhiều ngoại lệ trong Java 7 qua một ví dụ.
Bắt nhiều ngoại lệ trong Java 7
Trước Java 7, chúng ta thường bắt nhiều ngoại lệ một cách tuần tự như minh họa bên dưới.
catch (IOException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
catch (SQLException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}
Trong Java 7, chúng ta có thể bắt cả hai ngoại lệ này chỉ trong một catch block duy nhất như sau:
catch(IOException | SQLException ex){
logger.error(ex);
throw new MyException(ex.getMessage());
}
Nếu một catch block xử lý nhiều exception, bạn có thể tách chúng bằng ký hiệu pipe (|). Trong trường hợp này, tham số exception (ex) là final, nên bạn không thể thay đổi nó. Byte code (mã byte) được tạo ra bởi tính năng này nhỏ hơn và giúp giảm sự dư thừa của code.
Java rethrow exception
Một cải tiến khác nằm ở việc compiler (trình biên dịch) phân tích các ngoại lệ được ném lại (rethrown exceptions). Java rethrow exception cho phép bạn chỉ định các loại ngoại lệ cụ thể hơn trong throws clause của khai báo phương thức. Hãy xem một ví dụ nhỏ sau:
package com.journaldev.util;
public class Java7MultipleExceptions {
public static void main(String[] args) {
try{
rethrow("abc");
}catch(FirstException | SecondException | ThirdException e){
//below assignment will throw compile time exception since e is final
//e = new Exception();
System.out.println(e.getMessage());
}
}
static void rethrow(String s) throws FirstException, SecondException,
ThirdException {
try {
if (s.equals("First"))
throw new FirstException("First");
else if (s.equals("Second"))
throw new SecondException("Second");
else
throw new ThirdException("Third");
} catch (Exception e) {
//below assignment disables the improved rethrow exception type checking feature of Java 7
// e=new ThirdException();
throw e;
}
}
static class FirstException extends Exception {
public FirstException(String msg) {
super(msg);
}
}
static class SecondException extends Exception {
public SecondException(String msg) {
super(msg);
}
}
static class ThirdException extends Exception {
public ThirdException(String msg) {
super(msg);
}
}
}
Như bạn thấy, trong phương thức rethrow, catch block đang bắt Exception nhưng nó không xuất hiện trong throws clause. Java 7 compiler sẽ phân tích toàn bộ try block để kiểm tra những loại ngoại lệ nào được ném và sau đó bị ném lại từ catch block.
Lưu ý rằng quá trình phân tích này sẽ bị vô hiệu nếu bạn thay đổi đối số của catch block.
Về tác giả
Bao TranWeb Developer
I’m passionate about web development and sharing my insights through articles, with over 8 years of experience. I hope these sharings inspire you and help build a strong web development community.
@#@
Tôi đam mê phát triển web và chia sẻ những hiểu biết của mình thông qua các bài viết, với hơn 8 năm kinh nghiệm. Tôi hy vọng những chia sẻ này sẽ truyền cảm hứng cho các bạn và giúp xây dựng một cộng đồng phát triển web mạnh mẽ.
Cập nhật thông tin mới nhấtNhận các thông tin mới nhất về mối đe dọa, báo cáo an ninh mạng từ CyStack về hòm thư điện tử của bạn
Thảo luận (0)
Đăng nhập để thảo luận
Bài viết liên quan
{"success":true,"head":"<title>Java 7: Cách bắt nhiều ngoại lệ trong cùng một catch block - CyStack Tutorial</title>\n<meta name=\"description\" content=\"Trong Java 7, catch block đã được cải tiến để xử lý nhiều exception trong một catch block duy nhất.\"/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-video-preview:-1, max-image-preview:large\"/>\n<link rel=\"canonical\" href=\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/\" />\n<meta property=\"og:locale\" content=\"en_US\" />\n<meta property=\"og:type\" content=\"article\" />\n<meta property=\"og:title\" content=\"Java 7: Cách bắt nhiều ngoại lệ trong cùng một catch block - CyStack Tutorial\" />\n<meta property=\"og:description\" content=\"Trong Java 7, catch block đã được cải tiến để xử lý nhiều exception trong một catch block duy nhất.\" />\n<meta property=\"og:url\" content=\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/\" />\n<meta property=\"og:site_name\" content=\"CyStack Tutorial\" />\n<meta property=\"article:tag\" content=\"vi\" />\n<meta property=\"article:section\" content=\"Java\" />\n<meta property=\"article:published_time\" content=\"2025-08-30T08:05:58+07:00\" />\n<meta name=\"twitter:card\" content=\"summary_large_image\" />\n<meta name=\"twitter:title\" content=\"Java 7: Cách bắt nhiều ngoại lệ trong cùng một catch block - CyStack Tutorial\" />\n<meta name=\"twitter:description\" content=\"Trong Java 7, catch block đã được cải tiến để xử lý nhiều exception trong một catch block duy nhất.\" />\n<meta name=\"twitter:label1\" content=\"Written by\" />\n<meta name=\"twitter:data1\" content=\"Bao Tran\" />\n<meta name=\"twitter:label2\" content=\"Time to read\" />\n<meta name=\"twitter:data2\" content=\"2 minutes\" />\n<script type=\"application/ld+json\" class=\"rank-math-schema\">{\"@context\":\"https://schema.org\",\"@graph\":[{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https://blog.cystack.org/tutorial/#person\",\"name\":\"CyStack Tutorial\"},{\"@type\":\"WebSite\",\"@id\":\"https://blog.cystack.org/tutorial/#website\",\"url\":\"https://blog.cystack.org/tutorial\",\"name\":\"CyStack Tutorial\",\"publisher\":{\"@id\":\"https://blog.cystack.org/tutorial/#person\"},\"inLanguage\":\"en-US\"},{\"@type\":\"ImageObject\",\"@id\":\"https://s2.cystack.net/tutorial/30080502/java-7-cach-bat-nhieu-ngoai-le.png\",\"url\":\"https://s2.cystack.net/tutorial/30080502/java-7-cach-bat-nhieu-ngoai-le.png\",\"width\":\"200\",\"height\":\"200\",\"inLanguage\":\"en-US\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":\"1\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":\"2\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial/category/java/\",\"name\":\"Java\"}},{\"@type\":\"ListItem\",\"position\":\"3\",\"item\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/\",\"name\":\"Java 7: C\\u00e1ch b\\u1eaft nhi\\u1ec1u ngo\\u1ea1i l\\u1ec7 trong c\\u00f9ng m\\u1ed9t catch block\"}}]},{\"@type\":\"WebPage\",\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/#webpage\",\"url\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/\",\"name\":\"Java 7: C\\u00e1ch b\\u1eaft nhi\\u1ec1u ngo\\u1ea1i l\\u1ec7 trong c\\u00f9ng m\\u1ed9t catch block - CyStack Tutorial\",\"datePublished\":\"2025-08-30T08:05:58+07:00\",\"dateModified\":\"2025-08-30T08:05:58+07:00\",\"isPartOf\":{\"@id\":\"https://blog.cystack.org/tutorial/#website\"},\"primaryImageOfPage\":{\"@id\":\"https://s2.cystack.net/tutorial/30080502/java-7-cach-bat-nhieu-ngoai-le.png\"},\"inLanguage\":\"en-US\",\"breadcrumb\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/#breadcrumb\"}},{\"@type\":\"Person\",\"@id\":\"https://blog.cystack.org/tutorial/author/baotran/\",\"name\":\"Bao Tran\",\"url\":\"https://blog.cystack.org/tutorial/author/baotran/\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https://secure.gravatar.com/avatar/0cdd33c02ec4a531fcf557b9c1ccc276df0c69031b2382c959bcf335248e840c?s=96&d=mm&r=g\",\"url\":\"https://secure.gravatar.com/avatar/0cdd33c02ec4a531fcf557b9c1ccc276df0c69031b2382c959bcf335248e840c?s=96&d=mm&r=g\",\"caption\":\"Bao Tran\",\"inLanguage\":\"en-US\"}},{\"@type\":\"BlogPosting\",\"headline\":\"Java 7: C\\u00e1ch b\\u1eaft nhi\\u1ec1u ngo\\u1ea1i l\\u1ec7 trong c\\u00f9ng m\\u1ed9t catch block - CyStack Tutorial\",\"keywords\":\"java 7,b\\u1eaft nhi\\u1ec1u ngo\\u1ea1i l\\u1ec7 trong Java 7\",\"datePublished\":\"2025-08-30T08:05:58+07:00\",\"dateModified\":\"2025-08-30T08:05:58+07:00\",\"articleSection\":\"Java\",\"author\":{\"@id\":\"https://blog.cystack.org/tutorial/author/baotran/\",\"name\":\"Bao Tran\"},\"publisher\":{\"@id\":\"https://blog.cystack.org/tutorial/#person\"},\"description\":\"Trong Java 7, catch block \\u0111\\u00e3 \\u0111\\u01b0\\u1ee3c c\\u1ea3i ti\\u1ebfn \\u0111\\u1ec3 x\\u1eed l\\u00fd nhi\\u1ec1u exception trong m\\u1ed9t catch block duy nh\\u1ea5t.\",\"name\":\"Java 7: C\\u00e1ch b\\u1eaft nhi\\u1ec1u ngo\\u1ea1i l\\u1ec7 trong c\\u00f9ng m\\u1ed9t catch block - CyStack Tutorial\",\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/#richSnippet\",\"isPartOf\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/#webpage\"},\"image\":{\"@id\":\"https://s2.cystack.net/tutorial/30080502/java-7-cach-bat-nhieu-ngoai-le.png\"},\"inLanguage\":\"en-US\",\"mainEntityOfPage\":{\"@id\":\"https://blog.cystack.org/tutorial/2025/08/30/java-7-cach-bat-nhieu-ngoai-le/#webpage\"}}]}</script>\n"}