Mobile/Kotlin
[Kotlin] #4 : 예외처리 230216
haheehee
2023. 2. 16. 11:47
728x90
++ 예외(exception) ++
- 실행 도중의 잠재적인 오류까지 검사할 수 없음 -> 실행되다가 비정상적으로 프로그램이 종료되는 경우
- 운영체제의 문제 (잘못된 시스템 호출의 문제)
- 입력값의 문제 (존재하지 않는 파일 혹은, 숫자 입력란에 문자 입력 등)
- 받아들일 수 없는 연산 (0으로 나누기 등)
- 메모리의 할당 실패 및 부족
- 컴퓨터 기계 자체의 문제 (전원 문제, 망가진 기억 장치 등)
try {
예외 발생 가능성 있는 문장
} catch (e: 예외처리 클래스명) {
예외를 처리하기 위한 문장
} finally {
반드시 실행되어야 하는 문장
}
- ArithmeticException : 산술과 관련된 Exception
- 스택의 추적 : e.printStackTrace() -> 보안과 연결될 수 있으므로 조심
- throw Exception(message: String) : 특정 조건에 따른 예외 발생
- 사용자 예외 정의 :
class <사용자 예외 클래스명>(message: String) : Exception(message)
package com.example.pp101
import java.lang.Exception
fun main() {
val a = 6
val b = 0
val c: Int
try {
c = a/b
} catch(e: Exception) {
println("Exception is handled.")
} finally {
println("finally 블록은 반드시 항상 실행됨")
}
}
0으로 나누었을 때 예외 처리하기
package com.example.pp105
import java.lang.Exception
fun main() {
var amount = 600
try {
amount -= 100
checkAmount(amount)
} catch(e: Exception) {
println(e.message)
}
println("amount: $amount")
}
fun checkAmount(amount: Int) {
if(amount < 1000) {
throw Exception("잔고가 $amount 으로 1000 이하입니다. ")
}
}
throw를 사용해 예외 발생시키기
package com.example.pp106
import java.lang.Exception
// 사용자 예외 클래스
class InvalidNameException(message: String) : Exception(message)
fun main() {
var name = "Kildong1234" // 숫자 포함 이름
try {
validateName(name)
} catch (e: InvalidNameException) { // 숫자가 포함된 예외 처리
println(e.message)
} catch (e: Exception) { // 기타 예외 처리
println(e.message)
}
}
fun validateName(name : String) {
if(name.matches(Regex(".*\\d+.*"))) { // 이름에 숫자가 포함되어 있으면 예외 던지기
throw InvalidNameException("Your name : $name : contains numerals.")
}
}
사용자 정의 예외
- name.matches(Regex(".*\\d+.*")) // 이름에 숫자가 포함되어 있으면 예외 던지기
728x90