> For the complete documentation index, see [llms.txt](https://gold.gitbook.io/kotlin/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gold.gitbook.io/kotlin/expression/try-catch.md). Agents can also search and read this documentation through its [MCP server](https://gold.gitbook.io/kotlin/~gitbook/mcp).

# 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
```
