Java : Notes on Runtime Exceptions
This article is to recap some common runtime exceptions in Java. It is an important habit to consider exceptions before writing and then deal with them to avoid unintended exceptions during program execution.
UnsupportedOperationException
Happens when an operation is not supported, often because the implementation does not provide support for it.
List<String> list = Collections.emptyList();
list.add("Hello");
// because a Collections.emptyList is static method in Collections class, inherited by AbstractList, so add / remove / set method are not applicable
IllegalStateException
Occurs when the state of an object is not as expected for the operation being performed.
// Example
public class Example {
private boolean initialized = true;
public void initialize() {
if (initialized) {
throw new IllegalStateException("Already initialized");
}
// Initialization logic
initialized = true;
}
}
// main
Example exp = new Example();
exp.initialize();
IllegalArgumentException
Happens when a method receives an argument that is not of the expected type or is otherwise invalid.
public static void method(int value) {
if (value < 0) {
throw new IllegalArgumentException("Value must be positive");
}
}
method(-1);
ArithmeticException
Occurs when an arithmetic operation (such as division by zero) is attempted but not valid.
int result = 10 / 0
NumberFormatException
Happens when attempting to convert a string into a numeric format, but the string does not contain a valid numeric representation.
String str = "abc";
int num = Integer.parseInt(str);
ClassCastException
Occurs when attempting to cast an object to a type it is not compatible with.
Object obj = new Integer(100);
String str = (String) obj;
ArrayIndexOutOfBoundsException
Happens when trying to access an index outside the bounds of an array
int[] arr = {1, 2, 3};
int num = arr[5]
NullPointerException
Occurs when trying to access or modify an object reference that has a null value.
String str = null;
int length = str.length();
System.out.println(length);
寫這篇文章來記錄一些常見或可能用到的 runtime exception handling。撰寫前預先考慮例外狀況然後處理它們還滿重要的,避免程式執行時出現非預期的錯誤。
- NullPointerException : 嘗試存取空指標所指向之物件,沒有處理好 null 時會發生
- ArrayIndexOutOfBoundsException : 嘗試存取數組邊界外的 index
- ClassCastException : 嘗試將 object 轉換為與其不兼容的 type 時發生
- NumberFormatException : 轉換非有效數字表示的字串到數字格式
- ArithmeticException : 無效計算錯誤 (例如 除以 0)
- IllegalArgumentException : 方法收到的參數不屬於預期類型或無效
- IllegalStateExceptionobject : 狀態與正在執行的操作的預期不符時發生
- UnsupportedOperationException : 操作不支援時就會出現,這邊例子是 .emptyList() 無法使用 add / remove / set method,因為是 Collections 類別 (繼承自 AbstractList)下的一個靜態方法