tonykang22 / study

0 stars 0 forks source link

[Kotlin & Spring] 10. 고급 예외처리 #119

Open tonykang22 opened 1 year ago

tonykang22 commented 1 year ago

고급 예외처리

use를 사용한 리소스 해제

public class Java_TryWithResources {

public static void main(String[] args) {

     try (PrintWriter writer = new PrintWriter("test.txt")) {
            writer.println("Hello World");
     } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
    }
} 

}


<br>

- 정확히는 `Closeable` 또는 상위 개념인 `Autoloseable` 인터페이스의 구현체에 대해서 자동으로 close 메서드를 호출한다.
- `Closeable` 인터페이스 구현하는 Writer

``` java
public abstract class Writer implements Appendable, Closeable



public class PrintWriter extends Writer {
...

        public void close() {
                try {
                        synchronized (lock) {
                                if (out == null) 
                                        return;
                                out.close();
                                out = null;
                        }
                }
                catch (IOException x) {
                        trouble = true;
                }
        }
}


FileWriter("test.txt")
        .use { it.write("Hello Kotlin") }




runCatching을 사용해 우아하게 예외처리하기

fun getStr(): Nothing = throw Exception("예외 발생 기본 값으로 초기화")

fun main () {

        val result = try {
                getStr()
        } catch (e: Exception) {
                println(e.message)
                "기본값"
        }

        println(result)
}
// 예외 발생 기본 값으로 초기화
// 기본값



val result2 = runCatching { getStr() }
        .getOrElse {
                println(it.message)
                "기본값"
        }
        println(result2)

// 예외 발생 기본 값으로 초기화
// 기본값



public inline fun <R> runCatching(block: () -> R): Result<R> {
        return try {
                Result.success(block())
        } catch (e: Throwable) {
                Result.failure(e)
        }
}



public companion object {

        public inline fun <T> success(value: T): Result<T> = Result(value)

        public inline fun <T> failure(exception: Throwable): Result<T> = Result(createFailure(exception))
}



public value class Result<out T> internal constructor (
        internal val value: Any?
): Serializable {

        public val isSuccess: Boolean get() = value !is Failure

        public val isFailure: Boolean get() = value is Failure

...
}




Result의 다양한 기능들

val result3 = runCatching { getStr() }
                .getOrNull()
        println(result3)
// null 반환



val result3: Throwable? = runCatching { getStr() }
                .exceptionOrNull()

result3?.let {
        println(it.message)
        throw it
}



val result3 = runCatching { getStr() }
        .getOrDefault("기본 값")

println(result3)
// 기본 값



val result3 = runCatching { getStr() }
        .getOrElse {
                println(it.message)
                "기본 값"
        }

println(result3)
// 예외 발생 기본 값으로 초기화
// 기본 값



val result3 = runCatching { getStr() }
        .getOrThrow()
// Exception in thread "main" java.lang.Exception: 예외 발생 기본 값으로 초기화



val result3 = runCatching { "안녕" }
        .map {
                it + "하세요"
        }.getOrThrow()

println(result3)
// 안녕하세요



val result3 = runCatching { "안녕" }
        .map {
                getStr()
        }.getOrDefault("기본값")

        println(result3)
// Exception in thread "main" java.lang.Exception: 예외 발생 기본 값으로 초기화


val result3 = runCatching { "안녕" }
        .mapCatching {
                getStr()
        }.getOrDefault("기본값")

println(result3)
// 기본값



val result3 = runCatching { "정상" }
        .recover {
                "복구"
        }.getOrNull()

        println(result3)
// 정상

// 실패시
val result3 = runCatching { getStr() }
        .recover {
                "복구"
        }.getOrNull()

        println(result3)
// 복구



val result3 = runCatching { getStr() }
        .recover {
                getStr()
        }.getOrDefault("복구")

        println(result3)
// Exception in thread "main" java.lang.Exception: 예외 발생 기본 값으로 초기화


val result3 = runCatching { getStr() }
        .recoverCatching {
                getStr()
        }.getOrDefault("복구")

        println(result3)
// 복구