# try - catch

* Java의 try - catch 와 비슷하다. 하지만 표현식으로 사용할 수 있어서 변수등에 값을 할당 할 수 있다.
* 정상적인 케이스에는 try 값이, exception 이 발생하면 catch 값이 할당된다.
* try, catch 는 { } 의 마지막 줄의 값을 반환한다.
* Java 와 마찬가지로 finally 도 제공하지만 optional 이다.

```java
//java
String value = "test"

int parsedInt;

try {
    parsedInt = Integer.parseInt(value);
} catch (NumberFormatException e) {
    e.printStactTrace();
    parsedInt = -1;
}

System.out.println(parsedInt);  // -1
```

```kotlin
//kotlin
//표현식으로서의 사용
val value = "test"

val parsedInt: Int? = try {
    value.toInt()
} catch (e: NumberFormatException) {
    -1
}

println(parsedInt)   // -1
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gold.gitbook.io/kotlin/expression/try-catch.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
