try ~ catch 문은 예외를 처리하는 문법이다
문제는 try ~ catch 문이 '무엇인가'가 아니라 '언제' 사용하는가 인데
원래 try ~ catch 문은 수많은 에러체크
코드를 간편화하기위한 문법이다.
예를들어 FileInputStream 객체를 생성한다고
가정해보면 예외처리 없이는 파일을 열 때마다 조건을 검사해줘야한다.
if(file1.isExist()){
fis1 = new FileInputStream(File1);
}else{
System.out.println("File1 isn't exist");
}
if(file2.isExist()){
fis2= new FileInputStream(File2)
}else{
System.out.println("File2 isn't exist");
}
if(file3.isExist()){
fis3= new FileInputStream(File3);
}else{
System.out.println("File3 isn't exist");
}
하지만, 예외라는 것은 말그대로 예측할 수 없는 것인데. 확실하지도 않은 일로 일일히
검사코드를 작성하는 것은 불편하고, 소스코드의 가독성을 현저히 떨어뜨린다.
그래서 try ~ catch 문이 필요한것인데. 즉, 본래 try ~ catch의 목적은
'처음부터 일일히 신경쓰지말고, 따로 예외가 발생하면 처리하자'
라는 개념이다 .
위소스를 try catch로 변환한 예제
try{
fis1 = new FileInputStream(File1);
fis2 = new FileInputStream(File2)
fis3 = new FileInputStream(File3);
}catch(FileNotFoundException e){
System.out.println("File not found");
}
try catch 다른 예제
try{
for(int i=0;i<7;i++)
a[i]; //배열이 5개 이면 6번 째오류가 난다
}
catch(Exception e)
{
System.out.println("배열의 수를 넘었습니다"); //그럼 프로그램이 종료가 안대고 "배열의 수를 넘었습니다" 라고 출력이 될 것이다
}
댓글
댓글 쓰기