Skip to content

Commit

Permalink
[Week1][입문편]7강.코틀린에서 예외를 다루는 방법(#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
gyehwan24 committed May 19, 2024
1 parent f8426ef commit 91df6e6
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
28 changes: 28 additions & 0 deletions 백계환/입문/section2/7강_강의노트.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
## 7강 코틀린에서 예외를 다루는 방법
### 1. try catch finally 구문
```kotlin
fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch (e: NumberFormatException) { // 타입이 뒤에 위치
throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다.")
}
}
```
- try catch 문법 자체는 자바와 동일하다.
- try catch 도 `Expression`으로 간주된다.
```kotlin
fun parseIntThrow2(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) {
null
}
}
```
### 2. Checked Exception과 Unchecked Exception
- Kotlin에서는 Checked Exception과 Unchecked Exception을 구분하지 않는다.
- 모두 **Unchecked Exception**이다.
- 사실상 `throws`를 사용할 일이 없다.
### 3. try with resources
- Kotlin에서는 `try with resources` 구문이 사라지고 `use`라는 inline 확장함수를 사용한다.
22 changes: 22 additions & 0 deletions 백계환/입문/section2/lec07/FilePrinter.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package section2.lec07

import java.io.BufferedReader
import java.io.File
import java.io.FileReader

class FilePrinter {

fun readFile() {
val currentFile = File(".")
val file = File(currentFile.absolutePath + "/a.txt")
val reader = BufferedReader(FileReader(file))
println(reader.readLine())
reader.close()
}

fun readFile(path: String) {
BufferedReader(FileReader(path)). use { reader ->
println(reader.readLine())
}
}
}
19 changes: 19 additions & 0 deletions 백계환/입문/section2/lec07/Lec07Main.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package section2.lec07

import java.lang.IllegalArgumentException

fun parseIntOrThrow(str: String): Int {
try {
return str.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException("주어진 ${str}는 숫자가 아닙니다.")
}
}

fun parseIntThrow2(str: String): Int? {
return try {
str.toInt()
} catch (e: NumberFormatException) {
null
}
}

0 comments on commit 91df6e6

Please sign in to comment.