在Java應用程序中,處理異常的主要方法是使用try-catch語句
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// 可能會拋出異常的代碼
int result = riskyOperation();
System.out.println("Result: " + result);
} catch (Exception e) {
// 處理異常的代碼
System.err.println("An exception occurred: " + e.getMessage());
}
}
private static int riskyOperation() throws ArithmeticException {
int a = 10;
int b = 0;
return a / b; // 這將導致ArithmeticException(除以零)
}
}
public class ExceptionHandlingWithFinally {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("example.txt");
// 讀取和處理文件內容的代碼
} catch (IOException e) {
System.err.println("An I/O exception occurred: " + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close(); // 確保文件輸入流被正確關閉
} catch (IOException e) {
System.err.println("Failed to close the file input stream: " + e.getMessage());
}
}
}
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateInput("invalid_input");
} catch (InvalidInputException e) {
System.err.println("Invalid input: " + e.getMessage());
}
}
private static void validateInput(String input) throws InvalidInputException {
if (input == null || input.isEmpty()) {
throw new InvalidInputException("Input cannot be null or empty");
}
// 其他驗證邏輯
}
static class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
}
public class MultipleCatchBlocks {
public static void main(String[] args) {
try {
performDifferentOperations();
} catch (ArithmeticException e) {
System.err.println("An arithmetic exception occurred: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("An array index out of bounds exception occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("An unexpected exception occurred: " + e.getMessage());
}
}
private static void performDifferentOperations() {
// 可能會拋出不同類型異常的代碼
}
}
public class ExceptionChaining {
public static void main(String[] args) {
try {
processData();
} catch (DataProcessingException e) {
System.err.println("Data processing failed: " + e.getMessage());
e.printStackTrace();
}
}
private static void processData() throws DataProcessingException {
try {
readData();
} catch (IOException e) {
throw new DataProcessingException("Failed to read data", e);
}
}
private static void readData() throws IOException {
// 讀取數據的代碼,可能會拋出IOException
}
static class DataProcessingException extends Exception {
public DataProcessingException(String message, Throwable cause) {
super(message, cause);
}
}
}
通過使用這些方法,你可以更有效地處理Java應用程序中的異常。