[IT]/java
java.Exception Handling(예외 처리).throws
givemebro
2021. 3. 10. 10:51
반응형

throws
예외 Exception을 던진다는 의미
해당 메서드가 실행시 예외 상황을 만나면 특정 Exception을 메서드를 호출한 측으로 던질 수도 있다는 의미
호출한 메서드가 throws하면 해당 Exception을 try/catch 혹은 throws를 해야함
ex) rv.readMemo("파일명")--call-->public void readMemo(String fileName) throws XXXException{
정상적인 상황일때는 파일을 읽는다
만약 예외상황일 때는 예외를 호출한 곳으로 전달한다}
package step2;
import java.io.FileNotFoundException;
import java.io.FileReader;
class MemoService {
// throws : 호출한 측으로 예외 발생시 해당 Exception 객체를 전달하겠다는 의미
public void readMemo(String filePath) throws FileNotFoundException {
FileReader fr = new FileReader(filePath);
System.out.println(filePath + "의 파일 정보를 읽는 작업을 수행");
}
}
public class TestThrows1 {
public static void main(String[] args) throws FileNotFoundException {
MemoService service = new MemoService();
try {
service.readMemo("C:\\k215\\a.txt");
} catch (FileNotFoundException e) {
System.out.println("file이 없어서 읽을 수가 없도다. 파일명을 다시 확인해달라.");
// e.printStackTrace();
}
System.out.println("프로그램 정상 수행");
}
}
/*
C:\k215\a.txt의 파일 정보를 읽는 작업을 수행
프로그램 정상 수행
*/
package step2;
import java.io.FileNotFoundException;
import java.io.FileReader;
class MemoService {
// throws : 호출한 측으로 예외 발생시 해당 Exception 객체를 전달하겠다는 의미
public void readMemo(String filePath) throws FileNotFoundException {
FileReader fr = new FileReader(filePath);
System.out.println(filePath + "의 파일 정보를 읽는 작업을 수행");
}
}
public class TestThrows1 {
public static void main(String[] args) throws FileNotFoundException {
MemoService service = new MemoService();
try {
service.readMemo("C:\\k215\\b.txt");
} catch (FileNotFoundException e) {
System.out.println("file이 없어서 읽을 수가 없도다. 파일명을 다시 확인해달라.");
// e.printStackTrace();
}
System.out.println("프로그램 정상 수행");
}
}
/*
file이 없어서 읽을 수가 없도다. 파일명을 다시 확인해달라.
프로그램 정상 수행
*/
java.Exception Handling(예외 처리)
Excetion Handling(예외 처리) Exception : 예외 / Error : 에러 Exception Handling(예외처리) : 프로그램 실행시 예외적 상황 발생에 대한 대안흐름(대처방안)을 실행하고 프로그램을 정상 수행하는데 있음 > E..
broscoding.tistory.com
반응형