test3 .java
import java.io.*;
// 이건 인터넷에서 찾은, IOexception 관련 코드 입니다.
class Example {
public static void main(String args[])
{
FileInputStream fis = null;
/*This constructor FileInputStream(File filename)
* throws FileNotFoundException which is a checked
* exception*/
fis = new FileInputStream("B:/myfile.txt");
int k;
/*Method read() of FileInputStream class also throws
* a checked exception: IOException*/
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
/*The method close() closes the file input stream
* It throws IOException*/
fis.close();
}
}
/*이 코드를 컴파일 하면
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException
이런 오류를 볼 수 있습니다.
이유는 각 주석을 확인해도 알 수 있지만, checked exception인 FileNotFoundException 사용에 있어서
catch - declare 의 부재가 원인으로 아래와 같이 바꿔주면 정상적으로 실행 됨을 알 수 있습니다.
*/
class test3 {
public static void main(String args[])
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("B:/myfile.txt");
}
catch(FileNotFoundException fnfe)
{
System.out.println("The specified file is not " +
"present at the given path");
}
int k;
try
{
while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}
fis.close();
}
catch(IOException ioe)
{
System.out.println("I/O error occurred: "+ioe);
}
}
}
// 이를 통해 checked exception은 catch-declare가 꼭 이뤄져야 하며,
// unchecked는 꼭 필요하지 않다는 것을 (sub2 참조) 수 있었습니다.
/* 위 소스코드는 웹페이지
* http://beginnersbook.com/2013/04/java-checked-unchecked-exceptions-with-examples/
* 에서 가져왔습니다.*/