- try catch ๊ตฌ๋ฌธ์ ์ฌ์ฉํ์ง ์๊ณ , ๋ฉ์๋ ์ ์ธ๋ถ์ throws ํค์๋๋ฅผ ์ ์ธํ์ฌ ์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ค.
public void fileIn(String path) throws IOException {}
- ์์ธ๊ฐ ๋ฐ์ํ ๋ฉ์๋์์ ์์ธ์ฒ๋ฆฌ๋ฅผ ์งํํ์ง ์๊ณ , ์ด ๋ฉ์๋๋ฅผ ํธ์ถํ ๊ณณ์์ ์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ค.
- main()(๋ฉ์ธ ํจ์)์์ throws๋ฅผ ์ฌ์ฉํ๋ฉด ๊ฐ์๋จธ์ (JVM)์์ ์ฒ๋ฆฌ๋๋ค.
try {
// ์คํํ ๊ตฌ๋ฌธ
} catch(Exception e) { // ๋ฐ์ํ๋ Exception์ ์์ ์ ์ด์ค๋ค.
// ์๋ฌ๊ฐ ๋ฐ์ํ๋ ๊ฒฝ์ฐ ์ฒ๋ฆฌํด์ผ ํ๋ ๊ตฌ๋ฌธ
} finally {
// ์์ธ์ ๋ฐ์์ฌ๋ถ์ ์๊ด์์ด ๋ฌด์กฐ๊ฑด ์คํ๋๋ ๊ตฌ๋ฌธ
}
- ๋ค์ค ์์ธ ์ฒ๋ฆฌ
- ์์ธ์ ๊ฐ์ฅ ์์ Class์ธ Exception Class์ ๊ฒฝ์ฐ ๊ฐ์ฅ ๋ง์ง๋ง catch๋ฌธ์ ์์นํด์ผ ํ๋ค.
- ๋ง์ผ ๊ฐ์ฅ ์๋จ์ catch๋ฌธ์ Exception์ ์ ์ธํ๋ ๊ฒฝ์ฐ ๊ทธ ํ์์๋ Unreachable catch block์ด๋ผ๋ ์๋ฌ ๋ฌธ๊ตฌ๊ฐ ๋ฐ์ํ๋ค.
// ์ ์์ ์ธ ๊ฒฝ์ฐ
try {
~~~
} catch(IOException ioe) {
~~~
} catch(ClassNotFoundException cnfe) {
~~~
} catch(Exception e) {
~~~
}
// Exception Class๋ฅผ ๊ฐ์ฅ ์๋จ์ catch๋ฌธ์ ์ ์ธํ ๊ฒฝ์ฐ
try {
~~~
} catch(Exception e) {
~~~
} catch(ClassNotFoundException cnfe) { // Unreachable catch block for ClassNotFoundException.
~~~
} catch(IOException ioe) { // Unreachable catch block for IOException.
~~~
}
- ์ฌ์ฉ์ ์ ์ ์์ธ
- JDK์์ ์ ๊ณตํ๋ Exception Class์ธ์ ์ฌ์ฉ์๊ฐ ํ์์ ์ํด Exception Class๋ฅผ ์ ์ํ์ฌ ์ฌ์ฉํ๋ค.
- Exception Class๋ฅผ ์์๋ฐ์ ์ฌ์ฉ์๊ฐ ์ ์ํ๋ Exception Class๋ฅผ ์์ฑํ ์ ์๋ค.
public class IDFormatException extends Exception { public IDFormatException(String message) { super(message); } } public class IDFormatTest { public void setUserID(String userId) throws IDFormatException { if (userId == null) { throw new IDFormatException("ID๋ null์ผ ์ ์์ต๋๋ค.") } else if(userId.length() < 8 || userId.length > 20) } throw new IDFormatException("ID๋ 8์ ์ด์ 20์ ์ดํ์ฌ์ผ ํฉ๋๋ค.") } this.userId = userId; } ~~~ }
- Input/Output ๊ธฐ์ค ๋ถ๋ฅ : ์ ๋ ฅ ์คํธ๋ฆผ, ์ถ๋ ฅ ์คํธ๋ฆผ
- ์๋ฃ์ ์ข ๋ฅ ๊ธฐ์ค ๋ถ๋ฅ : ๋ฐ์ดํธ ์คํธ๋ฆผ, ๋ฌธ์ ์คํธ๋ฆผ
- ๊ธฐ๋ฅ๋ณ ๋ถ๋ฅ : ๊ธฐ๋ฐ ์คํธ๋ฆผ, ๋ณด์กฐ ์คํธ๋ฆผ
- Input Stream : ์๋ฃ๋ฅผ ์ฝ์ด ๋ค์ด๋ Stream
(ex : FileInputStream, FileReader, BufferedInputStream, BufferedReader etc...) - Output Stream : ์๋ฃ๋ฅผ ์ถ๋ ฅํ๋ Stream
(ex : FileOutputStream, FileWriter, BufferedOutputStream, BufferedWriter etc...)
- Byte Stream : Byte ๋จ์๋ก ์๋ฃ๋ฅผ ์ฝ๊ณ ์ด๋ค.(๋์์, ์์
ํ์ผ ๋ฑ)
(ex : FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream etc...) - Character Stream : 2Byte ๋จ์๋ก ์๋ฃ๋ฅผ ์ฝ๊ณ ์ด๋ค.
(ex : FileReader, FileWriter, BufferedReader, BufferedWriter etc...)
- Base Stream : ๋์ฌ์ ์๊ฒ ์ง์ ์๋ฃ๋ฅผ ์ฝ๊ณ ์ฐ๋ ๊ธฐ๋ฅ์ ์คํธ๋ฆผ
(ex : FileInputStream, FileOutputStream, FileReader, FileWriter etc...) - Object Stream : ์ง์ ์ฝ๊ณ ์ฐ๋ ๊ธฐ๋ฅ์ ์์ง๋ง ์ถ๊ฐ์ ์ธ ๊ธฐ๋ฅ์ ์ ๊ณตํด ์ฃผ๋ ์คํธ๋ฆผ, ๊ธฐ๋ฐ ์คํธ๋ฆผ์ด๋ ๋ ๋ค๋ฅธ ๋ณด์กฐ ์คํธ๋ฆผ์ ์์ฑ์์ ๋งค๊ฐ๋ณ์๋ก ํฌํจํ๋ค. (ex : InputStreamReader, OutputStreamWriter, BufferedInputStream, BufferedOutputStream etc...)
โป ๋ค์ Stream์ด ๋ถ์ผ๋ฉด Byte Stream์ด๊ณ , Reader๋ Writer๊ฐ ๋ถ์ผ๋ฉด Character Stream์ด๋ค.