---
# System prepended metadata

title: Java 錯誤處理for Debugging
tags: [debug, java, exception]

---

# Java 錯誤處理for Debugging
###### tags: `exception` `debug` `java`
## concepts
**e=error 是內建的變數**
**exception 是一種資料型態**
**try...catch...是偵錯專用語法**

## [types of exception in java](https://www.google.com/amp/s/www.geeksforgeeks.org/types-of-exception-in-java-with-examples/amp/)

## 加上 try{...}catch(){...}
**為了避免直接顯示編譯失敗或編譯中斷，利用exception來做例外處理**
### syntax
```java
try{[original code]}catch([exception type] e){print想要的錯誤訊息］}
```
```java=1
try{	
	String gender=id.substring(1,2);
				
	if(gender.equals("1")){
		System.out.println("男");
	}else if(gender.equals("2")){
		System.out.println("女");
	}else{
		System.out.println("輸入錯誤");
	}
}catch(StringIndexOutOfBoundsException e){
	System.out.println("輸入資料長度不足");
	return;
}
```

### 同時偵測兩種錯誤類型
```java
public void doNotCloseResourceInTry() {
    FileInputStream inputStream = null;
    try {
        File file = new File("./tmp.txt");
        inputStream = new FileInputStream(file);
        // use the inputStream to read a file
        // do NOT do this
        inputStream.close();
    } catch (FileNotFoundException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }
}
```
### finally
**若exception成立，則執行...**
**優點：裡面可再寫try...catch...**
```java
public void closeResourceInFinally() {
    FileInputStream inputStream = null;
    try {
        File file = new File("./tmp.txt");
        inputStream = new FileInputStream(file);
        // use the inputStream to read a file
    } catch (FileNotFoundException e) {
        log.error(e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
}
```