0%

200814 TIL

Wrapper Class

  • 기본형 타입을 객체로 쓰기 위해 있는 클래스
  • 기본형 타입이 허용되지 않는 문법에 기본형 타입을 쓰기 위해서 사용
Type Wrapper Class
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
  • Examples
1
2
3
4
5
public static Integer add(Integer x, Integer y) {
return x + y; // Unboxing
// 자동으로 기본자료형으로 변형되어서 계산
// 반환시 다시 Autoboxing 이루어짐
}
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 WrapperClass {
public static <T> T bypass(T x) {
return x;
}

public static void main(String[] args) {
Integer integer = new Integer(10); // Deprecated.., not recomended
Integer integer1 = Integer.valueOf(10);

Character character = new Character('d');
Character character1 = Character.valueOf('f');

// Autoboxing
Integer integer2 = 4;
System.out.println(add(4, 2));

bypass(5); // autoboxing
// T: Wrapper class인 Integer로 결정됨
// 5 -> new Integer(5), Autoboxing

// 문자열 <-> 기본 자료형
int x = Integer.parseInt("100"); // recommended, parse+자료형, 정적 메소드, 리턴 타입이 int임
int z = Integer.valueOf("200"); // return type Integer unboxing
}
}

Errors / Exceptions

오류 (Errors)

  • 메모리 부족 또는 프로그램 실행이 꼬이는 경우.
  • 더이상 어떻게 프로그램을 복구해야 할지 알 수 없다.
  • 프로그램의 문제를 해겷하여 해결

예외 (Exceptions)

  • 오류(Error)에 비해서 심각도가 낮고, 프로그램의 정상적인 흐름만 방해
    • 파일을 읽으려 했으나 해당 파일이 없는경우
    • 네트워크 연결 유실
  • 문제 상황을 처리하는 로직을 구현하여, 런타임에서 자연스럽게 해결 가능

예외 처리 (Excpetion handling)

  • 예외가 발생 했을 경우, 이 상황을 ‘감지’하고 ‘처리’하는 코드
  • try ~ catch, throws, throw, finally 키워드들을 이용
  • Throwable 클래스를 상속하는 자식클래스들로 이러한 문제를 해결

Throwable Class

  • Throwable 클래스는 ExceptionError 클래스에 의해 상속

    • Exception

      • Checked Exceptions: 예외 처리되지 않으면 컴파일이 되지 않은 예외 (file I/O)

        • Exception Class를 상속하고 있으면 Checked Exception
        • try ~ catch를 통해 예외를 꼭 처리해 주어야 컴파일이 된다.
      • Unchecked Exceptions: 예외 처리되지 않아도 컴파일이 되는 예외

        • RuntimeException 클래스를 상속하고 있으면 Unchecked Exception
        • try ~ catch를 작성하지 않더라도 빌드/실행 가능
        • ArrayIndexOutOfBoundsExceptions
        • ArithmeticException
    • Error: 프로그램이 복구 불가능한 상황

메소드 설명
public String getMessage() 발생한 예외에 대한 메세지를 반환
public String getLocalizedMessage() 오버라이드하여 추가 메세지 제공 (오버라이드하지 않으면 getMessage()와 동일)
public Throwable getCause() 예외의 원인이 되는 Throwable 객체 반환
public void printStackTrace() 예외가 발생된 메소드가 호출될 때의 Method call stack을 출력

try ~ catch statement

1
2
3
4
5
6
7
try {
// 예외가 발생할 수 있는 코드
// 예외가 발생할 경우 예외 객체를 던짐 (throw)
} catch (Exception e) { // 던져진 예외를 받음 (catch)
// Exception class 및 그 자식 클래스를 사용
// 예외 상황을 처리해야 하는 코드
}
  • example
1
2
3
4
5
6
7
try {
int[] integers = new int[10];
integers[20] = 5;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

Multiple Exception Handling

  • 여러 개의 catch 구문을 사용하면 다중 예외를 처리할 수 있음
  • 순차적으로 검사하면서 적용가능한 예외를 처리
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
try {
// 아주 예민한 내용이 실행되는 부분
// 특정 catch 구문에 선택되는 조건문
// 다형성에 의해서 결정 된다.
// 즉, catch 하고 있는 클래스의 자식 클래스의 객체면 catch 가능
// catch 하는 순서가 중요 -> 위에서 부터 자식 객체인 것이 좋다.
} catch (ArithmeticException e) {

} catch (FileAlreadyExistsException e) {

} catch (EOFException e) {

} catch (IOException e) {

} catch (Exception e) { // 나머지 모든 Exception 모두 catch
// 모든 Exception 객체의 조상
// 권장하지 않음, 무책임한 catch 이다.
}

try ~ catch ~ finally

  • try 구문 실행 중에 어떤 일이 발생해도 반드시 실행되어야 하는 구문은 finally block에 작성
  • try 구문 내에 return 문이 있는 경우에도 finally 블록은 실행됨
  • try 구문 내에서 접근한 System 자원을 안전하게 복구하기 위해 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
try {
file = new FileInputStream("a.txt");
file.read();
} catch (IOException e) {
System.out.println("파일 처리 실패");
} finally {
System.out.println("파이널리");
if (file != null) { // file 읽기에 실패한 경우 파일을 닫아준다.
try {
file.close();
} catch (IOException e) {
System.out.println("앗!... 아아...");
}
}
}

try ~ with ~ resource statement

  • Java1.7에서 추가된 기능
  • AutoClosable interface를 구현하는 리소스에만 사용가능
1
2
3
4
5
try (FileInputStream file1 = new FileInputStream("a.txt")) {
file1.read();
} catch (IOException e) {
System.out.println("파일 처리 실패");
}

Specifying the Exceptions Thrown by a Method

  • Checked Exception의 경우
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CheckedExceptionThrow {
void methodA() throws IOEception {
FileInputStream file1 = new FileInputStream("a.txt");
file1.read();
file1.close();
}

void methodB() /*throws*/ {
try {
methodA();
} catch (IOException e) {
System.out.println("메소드에실패")
}
}
}
  • Unchecked Exception: throws 키워드 사용하지 않아도 가능
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class UncheckedExceptionThrows {
void methodA() {
int x = 10 / 0;
}

void methodB() {
methodA();
}

public static void main(String[] args) {
try {
new UncheckedExceptionThrow().methodB();
} catch (ArithmeticException e) {
e.getMessage();
}
}
}
  • method를 override할경우 부모 class 의 method exception 보다 저 조상인 exception은 던질 수 없다.
1
2
3
4
5
6
7
8
9
10
11
class Foo {
void methodA() throws IOException {} // Checked Exception
}

class BarOne extends Foo {
void methodA() throws IOException {} // possible
}

class BarTwo extends Foo {
void methodA() throws FileNotFoundEception {} // 자식 Exception은 pass 가능
}

throw

  • 예외를 발생 시키는 키워드
  • new 키워드로 새 Exception 객체를 생성하여 예외 내용을 작성
1
2
3
4
5
6
7
void exceptMethod() throws Exception {
...
if (Err) {
throw new Exception("Some Error"); // 예외 발생 및 Message 전달
}
...
}

Custom Exceptions

  • Exception 또는 RuntimeException Class를 상속하여 작성

    • Exception을 상속한경우 Checked Exception이 되어 반드시 예외를 처리해야 한다.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class MyException extends RuntimeException {
    enum ErrorCode {
    ERROR_A, ERROR_B;
    }

    private ErrorCode errorCode;

    public MyException(ErrorCode errorCode, String message) {
    super(message)
    this.erroCode = errorCode;
    }

    @override
    public String getLocalizedMessage() {
    String message = getMessage();
    ...
    return localizedMessage;
    }
    }