Day 17(8/24) Try~Catch, throws

2016. 8. 26. 17:07Programming/Java

**오늘 배운 내용**

1) Try ~ Catch 활용

2) Reader, Buffer 개념

3) throws 활용


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
public class L01TryCatch {
     public static void main(String[] args) {
  
      int[] c = {0,1,2,3};
      int i = 3;
      int j = 1;
      if(i<c.length && i>=0){
           if(c[j]!=0){
           System.out.println(c[i]/c[j]);
           }
      }else{
           System.out.println("오류가 발생해서 예외처리했습니다.");
      }
      try{
           System.out.println("try catch 실행 시작");
           System.out.println(c[i]/c[j]);
           System.out.println("나도 실행시켜줘");
      }catch(ArithmeticException e){
           System.out.println(e.toString()+"예외발생1");
      }catch(ArrayIndexOutOfBoundsException e){
           System.out.println(e.toString()+"예외발생2");
      }catch(Exception e){
           System.out.println(e.toString()+" 모든 예외의 조상");
      }finally{
           System.out.println("finally는 무조건 실행");
      }
  
  //예외가 발생하면 try catch 내부의 thread가 무시된다(밖으로 벗어난다)
  //중복으로 예외처리 가능
  //Exception은 모든 예외 처리가 가능하지만, 다른 클래스로 예외처리하면
  //try catch 내부에 어떤 오류가 발생할 수 있는지 참고할 수 있음
  //finally는 무조건 실행
 
  System.out.println("문제해결");  
 }
}
 
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.io.BufferedReader;//파일에 있는 문서 내용을 읽는다.
import java.io.FileNotFoundException;
import java.io.FileReader;//컴퓨터에 있는 파일을 읽고
import java.io.IOException;
 
class FileRead{
     String fileName;
     public FileRead(String fileName){
          this.fileName = fileName;
     }//생성자 end

     public void run() throws FileNotFoundException, IOException{//throws: 예외 위임
          try {
               FileReader fr = new FileReader(fileName);
               BufferedReader br = new BufferedReader(fr);
   //받아온 파일을 read()를 사용한 것처럼 화면에 출력
          String line;
          for(int i=0;(line = br.readLine())!=null;i++){
      {
System.out.println(line);
     }
   }
   
  } catch (FileNotFoundException e) {System.out.println(e.toString());
  } catch (IOException e){e.printStackTrace();}
 }
}
 
public class L03Throws {
 public static void main(String[] args){
  String fileName = "src/com/javalesson/ch15exception/L03Throws.java";
  //예외 위임 -> 예외 처리 (무책임하게) 떠넘기는 것
  //throws를 마지막 사용하는 곳(thread가 실행되는 곳)에서 사용하면 최종 예외처리로 throws가 인정됨
 
  System.out.println("출력되면 오류가 throws 된다.");
 }
}
cs



'Programming > Java' 카테고리의 다른 글

Day 19(8/26) 좌석 예약 시스템  (0) 2016.08.29
Day 18(8/25) 숫자 맞추기 게임, 가위바위보  (0) 2016.08.26
Day 16(8/22) ArrayList, HashMap, HashSet  (0) 2016.08.23
Day 15(8/19) Generic  (0) 2016.08.23
Day 14(8/18) Final, Enum  (0) 2016.08.23