Custom Exception là ngoại lệ do người dùng tự định nghĩa. Custom Exception trong Java được sử dụng để tùy biến ngoại lệ theo yêu cầu của người dùng. Bởi sự giúp đỡ của loại ngoại lệ này, người dùng có thể có riêng kiểu và thông điệp ngoại lệ riêng cho mình.
Thông thường, để tạo ra custom exception thuộc loại checked chúng ta kế thừa từ lớp Exception. Để tạo custom exception thuộc loại unchecked chúng ta kế thừa từ lớp RuntimeException.
Trong các ứng dụng thực tế, thông thường custom exception được tạo là checked exception.
Ví dụ:
Tạo ngoại lệ tùy chỉnh thuộc loại checked exception:
class InvalidAgeException extends Exception { InvalidAgeException(String s) { super(s); } }
Sử dụng ngoại lệ tùy chỉnh:
class CustomExceptionExample {
static void validate(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("not valid");
} else {
System.out.println("welcome to vote");
}
}
public static void main(String args[]) {
try {
validate(13);
} catch (Exception m) {
System.out.println("Exception occured: " + m);
}
System.out.println("rest of the code...");
}
}
Kết quả thực thi chương trình trên:
Exception occured: com.maixuanviet.throwex.InvalidAgeException: not valid
rest of the code...
Related posts:
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
Form Validation with AngularJS and Spring MVC
Instance Profile Credentials using Spring Cloud
ETags for REST with Spring
Java toString() Method
Apache Camel with Spring Boot
Checking for Empty or Blank Strings in Java
Spring Cloud – Tracing Services with Zipkin
Java Program to Find Basis and Dimension of a Matrix
String Operations with Java Streams
Multipart Upload with HttpClient 4
Giới thiệu về Stream API trong Java 8
Jackson – Marshall String to JsonNode
Java Program to Implement Naor-Reingold Pseudo Random Function
Introduction to Spring Cloud OpenFeign
Spring Boot - Actuator
Lập trình hướng đối tượng (OOPs) trong java
Java Program to find the peak element of an array using Binary Search approach
HashSet trong java
Assert an Exception is Thrown in JUnit 4 and 5
Spring Boot Annotations
@Lookup Annotation in Spring
Java Program to Represent Graph Using Adjacency Matrix
Java – Reader to String
Apache Tiles Integration with Spring MVC
Java Program to Check if a Directed Graph is a Tree or Not Using DFS
Java Program to Generate Randomized Sequence of Given Range of Numbers
Extract network card address
Java Program to Perform Complex Number Multiplication
Spring Boot - Cloud Configuration Server
Java Program to Implement Depth-limited Search
Hướng dẫn Java Design Pattern – Command