본문 바로가기

Programming/국비학원

220511 - 9장 문풀, 예외 처리(다중catch, 멀티catch, 예외 떠넘기기, 사용자정의예외), 10장 문풀, API(String)

9장 중첩 클래스, 중첩 인터페이스 확인문제
  • 4번 문제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Car {
    class Tire{}
    static class Engine{}
}
 
public class NestedClassEx1 {
 
    public static void main(String[] args) {
        Car myCar = new Car(); //먼저 부모클래스 객체 생성
        Car.Tire tire = myCar.new Tire();  
 
        Car.Engine engine = new Car.Engine();
        
    }
}
cs

 

 

  • 5번 문제
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
public class Anonymous {
    
    Vehicle field = new Vehicle() {  //필드
        public void run() {
            System.out.println("자전거가 달립니다");
        }
    };
            
    void method1() {  //메소드 내 로컬변수
        Vehicle localVar = new Vehicle(){
            public void run() {
                System.out.println("승용차가 달립니다");
            }
        };
        localVar.run();
    }
    
    void method2(Vehicle v) {  //매개변수 => 다형성(ex.bus, taxi)
        v.run();
    }
    
}
 
 
public class AnonymousEx1 {
 
    public static void main(String[] args) {
        Anonymous anony = new Anonymous();
        
        anony.field.run();  //필드
        anony.method1();  //로컬변수
        anony.method2(new Vehicle() {  //매개변수
            public void run() {
                System.out.println("트럭이 달립니다");
            }        
        });
    }
 
}
cs

 

 

  • 6번 문제
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
public class Chatting {
    
    void startChat(String chatId) {
        //String nickName  = null;
        //nickName = chatId; => 익명객체 내에서는 final 변수만 사용
        String nickName  = chatId;
        Chat chat = new Chat() {  //로컬 변수
            @Override
            public void start() {
                while(true) {
                    String inputData="안녕하세요";
                    String message=nickName+" "+inputData;
                    sendMessage(message);
                }
            }
        };
        chat.start();      
    }
    
    class Chat{
        void start() {}
        void sendMessage(String message) {}
    }
 
}
cs

 

 

 

예외 처리

: 사용자의 잘못된 조작, 개발자의 잘못된 코딩으로 인한 프로그램 오류 대응 (문법 오류 X)

 

 

  • 예외 처리 코드

try문에서 오류 발생 => 오류 코드 밑줄부터 try문 실행 X

finally : 예외 상관 없이 무조건 실행

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ExceptionEx5 {
 
    public static void main(String[] args) {
        
        try {
        String[] data = {"a100","200"};
        int value1=Integer.parseInt(data[0]);
        int value2=Integer.parseInt(data[1]);        
        int result = value1+value2;
        System.out.println("계산 결과 : "+result);
        catch(NumberFormatException e) {
            System.out.println("숫자만 입력해주세요");
        finally {
            System.out.println("모두 화이팅");
        }
        
    }
 
}
cs

//
계산 결과 : 300

 

 

  • 실행 예외

 : 컴파일 과정에서 예외처리코드를 검사하지 않음 (명시적 예외처리가 강제되지 않음 => 예외처리 놓쳤을 때 프로그램 실행 시 강제 종료될 수도 있음) <-> 일반 예외

RuntimeException 상속 클래스 => 컴파일러가 체크하지 않으므로 개발자 경험 기반 예외처리함

 

 

  • NullPointerException : null값 참조변수(객체 참조 없음)로 객체접근연산자 . 를 사용 시 발생
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ExceptionEx2 {
 
    public static void main(String[] args) {
        String name = "홍길동";
        System.out.println("이름 : "+ name.toString());  
        //name만 입력시 참조값에만 접근해서 출력, toString문자값 정보 찾아옴
    }
 
}
 
 
public class ExceptionEx2 {
 
    public static void main(String[] args) {
        try {
        String name = null;
        System.out.println("이름 : "+ name.toString());
        } catch (NullPointerException e) {
            System.out.println("문자정보 가져올 수 없음");
        }
    }
}
cs

=> 스택에 주소번지 없어지고 null 저장 -> 힙영역과 참조연결 끊긴 상태가 됨 -> 문자값 가져올 수 없음

 

 

참조타입(String) : 스택참조값(주소번지) 저장,문자값 저장
String hobby = "여행";
hobby = null;
=> 힙에는 "여행" 문자값 저장돼있으나 스택에는 null 저장되며 참조연결 끊김
=> 자바가 자동적으로 쓰레기수집기 구동시켜 "여행"값을 힙 메모리에서 제거할 것

 

 

  • ArrayIndexOutOfBoundsException : 배열의 인덱스 범위 초과
1
2
3
4
5
6
7
8
9
10
11
12
13
public class ExceptionEx3 {
 
    public static void main(String[] args) {
        
        try {
            int[] nums = {10,20,30,40,50};
            System.out.println(nums[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("배열의 인덱스 범위를 벗어났습니다");
        }
    }
 
}
cs

 

 

  • NumberFormatException : 숫자 변환 실패 시 (.parseInt, .parseDouble 사용)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ExceptionEx4 {
 
    public static void main(String[] args) {
        
        try {
        String data1="100";
        String data2="a200";
        System.out.println(data1+data2);
        
        int value1 = Integer.parseInt(data1);
        int value2 = Integer.parseInt(data2);
        System.out.println(value1+value2);
        } catch (NumberFormatException e) {
            System.out.println("숫자만 넣어주세요");
        }
        
    }
 
}
cs

 

 

  • ClassCastException : 상하위 클래스 관계가 아닌데 타입 변환 시도 시
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
public class Driver {
    //메소드
    void Drive(Vehicle vehicle) {  
        //if (vehicle instanceof Bus) {    //타입 물어보는 명령
            Bus bus=(Bus)vehicle;
            bus.checkFare();
        //}
        vehicle.run();
    }
}
 
 
public class DriverEx1 {
 
    public static void main(String[] args) {
        try {
        Driver chulsu = new Driver();
        Taxi taxi = new Taxi();
        Truck truck = new Truck();
        Bus bus = new Bus();
        chulsu.Drive(bus); //실행됨
        chulsu.Drive(taxi);  //예외 처리 시작
        chulsu.Drive(truck);
        } catch (ClassCastException e) {
            System.out.println("타입 변환할 수 없습니다");
        }
    }
}
cs

//

승차요금을 체크합니다.

버스가 달립니다.

타입 변환할 수 없습니다

 

 

  • 다중 catch

: 각각의 경우마다 사용자에게 어떤 오류인지 설명해주기 위해 다중 예외처리함

 

catch는 단 하나의 블록만 실행됨

=> try 블록에서 하나의 예외 발생하자마자 catch 블록으로 이동하기 때문 (동시 예외 발생 불가)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ExceptionEx5 {
 
    public static void main(String[] args) {
        
        try {
            String[] data = {"100","200"};
            int value1=Integer.parseInt(data[0]);
            int value2=Integer.parseInt(data[1]);        
            int result = value1+value2;
            System.out.println("계산 결과 : "+result);
        } catch(NumberFormatException e) {
            System.out.println("숫자로 변환할 수 없습니다");
        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("배열의 인덱스를 벗어났습니다");
        } catch(Exception e) {  
            System.out.println("프로그램 개발자에게 문의하세요"+e.getMessage());
        } finally {
            System.out.println("화이팅");
        }
        
    }
 
}
cs

=> Exception e 를 가장 마지막에 놓아야 함

=> catch문은 순차적으로 실행되므로 상위 예외처리부터 실행시킨 후 마지막에 기타 예외 실행

 

  • 멀티 catch (권장 X)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ExceptionEx6 {
 
    public static void main(String[] args) {
        
        try {
            String[] data = {"100","200"};
            int value1=Integer.parseInt(data[0]);
            int value2=Integer.parseInt(data[1]);        
            int result = value1+value2;
            System.out.println("계산 결과 : "+result);
        } catch(NumberFormatException|ArrayIndexOutOfBoundsException e) {    
            System.out.println("숫자로 변환할 수 없거나 배열의 인덱스를 벗어났습니다");
        } catch(Exception e) {
            System.out.println("프로그램 개발자에게 문의하세요"+e.getMessage());
        } finally {
            System.out.println("화이팅");
        }
        
    }
 
}
cs

 

 

  • 예외 떠넘기기

try-catch 문 대신 메소드 호출한 곳으로 예외 떠넘기기

 

 

1
2
3
4
5
6
7
8
9
10
11
12
public void method1(){
    try
        method2(); 
    }catch(ClassNotFoundException e){ //호출한 곳에서 예외 처리
       System.out.println("클래스가 존재하지 않습니다") 
    } 
 
 
public void method2() throws ClassNotFoundException{
    Class class = Class.forName("java.lang.String2");
}
cs

=> method1()에서도 다시 예외 떠넘기기 가능 -> method1 호출하는 곳에서 try-catch 사용해 예외 처리해야 함

ex. public void method1() throws ClassNotFoundException{method2();}

 

 

  • 사용자 정의 예외
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class BalanceInsufficientException extends Exception{
    //생성자
    public BalanceInsufficientException() {
    }
    
    public BalanceInsufficientException(String message) {
        super(message); //Exception 클래스의 생성자 호출
    }
}
 
 
public class Account {
//은행계좌 클래스(통장)
    //필드
    static final String BANKNAME = "신한은행";
    String accountNo;    
    String ownerName;    
    int balance;
    
    //생성자
    public Account(String accountNo, String ownerName, int balance) {
        this.accountNo=accountNo;  
        this.ownerName=ownerName;
        this.balance=balance;
    }
    
    public Account() {
    }
    
    //메서드: 예금
    void deposit (int amount) {    
        balance+=amount;
    }    
    //메서드: 인출
    int withdraw(int amount) throws BalanceInsufficientException {  
        if (balance<amount) {
            throw new BalanceInsufficientException("잔액 부족");
        } 
        balance-=amount;
        return amount;
    }    
}
 
 
public class AccountEx1 {
 
    public static void main(String[] args) {
        Account chulsu = new Account();
        chulsu.accountNo = "0101-10101-1010";  
        chulsu.ownerName = "김철수";
        chulsu.balance = 1000;
        
        Account gildong = new Account();
        gildong.accountNo = "0202-020202-0202";
        gildong.ownerName = "홍길동";
        gildong.balance = 0;
        
        chulsu.deposit(5000);
        gildong.deposit(30000);
        chulsu.deposit(20000);
    
        try {
            int amount = gildong.withdraw(70000);
            System.out.println("찾은 금액: "+amount);
        }catch(BalanceInsufficientException e) {
            System.out.println(e.getMessage());
        }
    }
}
cs

//
잔액 부족

 

 


????

try catch 문 각각 두개 있을 때 앞 try문에서 오류 발생해 catch 실행되면 뒤 try문도 실행 안 되는 이유

=> 예제에 return; 있어서 메소드 밖으로 나간 거였음

 

 

10장 예외 처리 확인문제
  •  

자바 표준 예외 + 사용자 정의 예외 => 예외

throws : 생성자나 메소드 선언 끝(=메소드 선언부)에 사용, 다중 예외 시 쉼표로 구분

throw : 예외를 최초로 발생시킴, throw 키워드 뒤는 예외 객체 생성 코드 (ex. throw new BalanceInsuff~)

 

 

  • 5번 문제

public void method1() throws NumberFormatException, ClassNotFoundException {...}

=> 예외 처리

1. try {method1();}catch(Exception e){}

2. void method2 throws Exception {method1();}

3. try {method1();}catch(ClassNotFoundException e){} catch (NumberFormatException e){}

 

 

  • 6번 문제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class practice {
 
    public static void main(String[] args) {
        String[] strArray = {"10","2a"};
        int value =0;
        for (int i=0;i<=2;i++) {
            try {
                value=Integer.parseInt(strArray[i]);
            }catch(ArrayIndexOutOfBoundsException e){
                System.out.println("인덱스 초과");
            }catch(NumberFormatException e) {
                System.out.println("숫자 변환 불가");
            }finally {
                System.out.println(value);
            }
        }
    }
 
}
cs

//

10

숫자 변환 불가

10

인덱스 초과

10

 

 

API


https://docs.oracle.com/en/
https://docs.oracle.com/en/java/javase/17/docs/api/index.html
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html

 

 

  • String

 

  • charAt : 입력한 숫자 위치의 String값을 char로 변환

공백도 숫자에 포함됨

 

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
public class StringEx1 {
 
    public static void main(String[] args) {
        
        //String str = new String("자바프로그래밍");
        String str = "자바프로그래밍";
        char ch = str.charAt(5);  //다섯번째 문자
        System.out.println(ch);
        
    }
 
}
//
 
 
//주민번호 문제
 
    public static void main(String[] args) {
    
        String ssn = "980101-1234567";
        char a = ssn.charAt(7);
 
        if (a=='1'||a=='3') {
            System.out.println("남");
        }else if (a=='2'||a=='4') {
            System.out.println("여");
        }else {
            System.out.println("주민번호 오류");
        }
        
    }
 
}
cs

 

 

  • indexof : 입력한 문자열이 시작하는 위치 반환

찾는 문자열이 존재하지 않으면 -1 반환

1
2
3
4
5
6
7
8
9
10
11
public class StringEx2 {
 
    public static void main(String[] args) {
 
       String str = "자바 프로그래밍";
        int index = str.indexOf("자바");
        System.out.println(index);
        
    }
 
}
cs

//

0

 

 

  • length : 공백 포함된 문자열의 길이

String str = "오늘 코로나 확진자 명단";
System.out.println(str.length());

//

13

 

 

 

  • getBytes : 바이트 크기 구함


영문 1글자 1byte
한글 1글자 2byte
(length에 반영 X)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class StringEx3 {
 
    public static void main(String[] args) {
    
        String str = "korea";
        System.out.println(str.length());
        
        byte[] bytes = str.getBytes();
        System.out.println(bytes.length);
        
    }
 
}
cs

//

5

5

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
public class StringEx3 {
 
    public static void main(String[] args) {
    
        String str = "안녕하세요";
        System.out.println(str.length());
        
        byte[] bytes = str.getBytes();
        System.out.println(bytes.length);
        
    }
 
}
cs

//

5

10

 

 

  • replace : 입력 문자열 a를 입력 문자열 b로 바꿈

String str = "지금은 자바의 API에 대해 배우고 있습니다. 자바는 풍부한 라이브러리를 제공합니다.";
String newStr = str.replace("자바", "Java");
System.out.println(str);
System.out.println(newStr);

//
지금은 자바의API에 대해 배우고 있습니다. 자바는 풍부한 라이브러리를 제공합니다.
지금은 Java의 API에 대해 배우고 있습니다. Java는 풍부한 라이브러리를 제공합니다.

 

 

  • substring : x번째부터 문자열 출력 / x번째부터 y-1번째까지 출력

String str = "computer";
String sub1=str.substring(5);
String sub2=str.substring(2, 5);
System.out.println(sub1);
System.out.println(sub2);
//
ter
mpu


String ssn="920812-1234567";
String ssn2=ssn.replace(ssn.substring(7), "*******");
System.out.println(ssn2);
//
920812-*******

 

 

  • toLowerCase : 영어를 전체 소문자로 변환

String original = "Java Programming";
String lower = original.toLowerCase();
System.out.println(lower);
//
java programming

String upper = original.toUpperCase();
System.out.println(upper);
//
JAVA PROGRAMMING

 

 

  • trim : 문자 옆 공백 삭제

String str = "  자바 프로그래밍    ";
String newStr = str.trim();
System.out.println(newStr);
//
자바 프로그래밍

 

 

  • valueOf : 숫자를 문자로 변환

String str2 = String.valueOf(10);
System.out.println(str2);