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 Check Multiplicability of Two Matrices
Hamcrest Collections Cookbook
Java Program to Implement Binary Tree
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Getting the Size of an Iterable in Java
Java Program to Check Whether Graph is DAG
Java Program to Generate a Graph for a Given Fixed Degree Sequence
Java Program to Optimize Wire Length in Electrical Circuit
Java Program to Solve the 0-1 Knapsack Problem
Java Program to Implement Quick sort
Loại bỏ các phần tử trùng trong một ArrayList như thế nào trong Java 8?
Spring Web Annotations
Comparing Objects in Java
Spring Data Reactive Repositories with MongoDB
Apache Tiles Integration with Spring MVC
Java Program to Implement Interval Tree
Java Program to Implement Repeated Squaring Algorithm
Giới thiệu Java Service Provider Interface (SPI) – Tạo các ứng dụng Java dễ mở rộng
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Introduction to PCollections
Introduction to the Java ArrayDeque
Removing all duplicates from a List in Java
Custom Error Pages with Spring MVC
Compact Strings in Java 9
Injecting Prototype Beans into a Singleton Instance in Spring
Spring Cloud – Adding Angular
How to Get a Name of a Method Being Executed?
Format ZonedDateTime to String
An Introduction to Java.util.Hashtable Class
Java Program to Solve Tower of Hanoi Problem using Stacks
Filtering and Transforming Collections in Guava
Convert Hex to ASCII in Java