포스팅 OS : Mac

검색어 : 코틀린(Kotlin), 에외(Exception), Try, Catch, Finally, Toast


▶︎ 이전 포스팅 목록

2018/02/10 - [Android_Kotlin] - [Android Kotlin] 안드로이드 스튜디오(Andorid Studio)에 코틀린(Kotlin) 개발환경 셋팅

2018/03/14 - [Android_Kotlin] - [Android Kotlin] 텍스트뷰(TextView)와 버튼(Button)을 사용한 헬로 코틀린

2018/03/14 - [Android_Kotlin] - [Android Kotlin] 함수와 변수를 이용하여 에디트텍스트(EditText)에 입력한 값 중 큰 값 구하기

2018/03/15 - [Android_Kotlin] - [Android Kotlin] 문자열 템플릿(String Template) 사용법

2018/06/05 - [Android_Kotlin] - [Android Kotlin] 클래스, 프로퍼티, 커스텀 접근자 - 라디오 버튼(Radio Button)



코틀린의 예외처리는 자바와 비슷합니다. 


다른 점이 있다면 코틀린에서는 체크 예외 처리를 강제하지 않습니다. 개발자들이 예외를 잡지만 처리는 하지 않고 무시하는 코드로 작성을 흔하게 하기에 이를 고려하여 자바와는 다르게 강제하지 않은 것이 아닐까 생각합니다. 


이 역시 예제로 한번 살펴 보겠습니다.




1. 레이아웃

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.kotlin_test.Main1Activity.ExceptionActivity">

<EditText
android:hint="문자 입력시 예외처리"
android:id="@+id/edt_ex_str"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"
android:gravity="center"
android:background="@null"/>

<Button
android:id="@+id/btn_ex1"
android:text="Try Catch Finally 사용 예외처리"
android:layout_width="match_parent"
android:layout_height="50dp" />
<Button
android:id="@+id/btn_ex2"
android:text="Try를 식으로 예외처리"
android:layout_width="match_parent"
android:layout_height="50dp" />
<Button
android:id="@+id/btn_ex3"
android:text="Catch에서 값 반환"
android:layout_width="match_parent"
android:layout_height="50dp" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_ex_log"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"
android:gravity="center"/>
</ScrollView>
</LinearLayout>





2. 소스

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.kotlin_test.R
import kotlinx.android.synthetic.main.activity_exception.*
import java.io.BufferedReader
import java.io.StringReader

class ExceptionActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_exception)

btn_ex1.setOnClickListener {
txt_ex_log.setText("")

val reader = BufferedReader(StringReader(edt_ex_str.text.toString()))

txt_ex_log.setText(readNumber1(reader).toString())
}

btn_ex2.setOnClickListener {
txt_ex_log.setText("")

val reader = BufferedReader(StringReader(edt_ex_str.text.toString()))

readNumber2(reader)
}

btn_ex3.setOnClickListener {
txt_ex_log.setText("")

val reader = BufferedReader(StringReader(edt_ex_str.text.toString()))

readNumber3(reader)
}
}

// 자바와 동일한 방식의 Try
fun readNumber1(reader: BufferedReader): Int? {
try {
val line = reader.readLine() // 자바로 이 부분을 처리하기 위해선 체크 예외를 명시적으로 처리해야 한다.
// 하지만 코틀린에서는 함수가 던질 수 있는 예외를 명시할 필요가 없다. (throws IOException을 붙이지 않아도 된다.)
return Integer.parseInt(line)
}
catch (e: NumberFormatException) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
return null
}
finally {
reader.close()
}
}

// Try를 식으로 사용하기
fun readNumber2(reader: BufferedReader) {
val number = try {
Integer.parseInt(reader.readLine())
} catch (e: NumberFormatException) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
return // 예외가 발생하면 return
}

txt_ex_log.setText(number)
}

// Catch에서 값 반환하기
fun readNumber3(reader: BufferedReader) {
val number = try {
Integer.parseInt(reader.readLine())
} catch (e: NumberFormatException) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show()
null // 예외가 발생하면 null 값을 사용
}

txt_ex_log.setText(number.toString())
}
}



3. 실행 결과


+ Recent posts