728x90
📙 1. 기본 try / catch / finally
Scala에서는 try문도 표현식(Expression)이며 try를 사용해 값을 반환할 수 있습니다.
import java.nio.file.{Files, Paths}
import java.nio.charset.StandardCharsets
object TryCatchFinallyExample {
def main(args: Array[String]): Unit = {
val outputPath = Paths.get("output.txt"); // 한글 출력 파일
val sb = new StringBuilder()
try {
val num = "123a".toInt // NumberFormatException 에러 발생
sb.append(s"변환된 숫자: $num\n")
} catch {
case e: NumberFormatException =>
sb.append("숫자로 변환할 수 없습니다!");
case e: Exception =>
sb.append("기타 예외 발생: " + e.getMessage)
} finally {
sb.append("무조건 실행되는 finally");
}
// UTF-8 파일 작성
Files.write(outputPath, sb.toString.getBytes(StandardCharsets.UTF_8));
sb.append("출력완료!: output.txt에 저장되었습니다.");
}
}
- C, Java, C#과 비슷한 예외 처리 방식
- 예외 발생시 catch로 잡고 finally는 항상 실행됨
📙 2. Try / Success / Failure
함수형 스타일의 예외 처리 방식으로 예외 발생 여부를 값(Success or Failure)으로 감싸서 다룹니다. 프로그램이 멈추지 않고 안전하게 흐름을 이어갈 수 있습니다.
import scala.util.{Try, Success, Failure}
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}
object TrySuccessFailureExample {
def main(args: Array[String]): Unit = {
val outputPath = Paths.get("output.txt"); // 한글 출력 파일
val result = Try("123a".toInt) // 실패할 수 있는 코드
val sb = new StringBuilder()
result match {
case Success(value) =>
sb.append(s"성공: $value")
case Failure(exception) =>
sb.append(s"실패: ${exception.getMessage}")
}
// UTF-8 파일 작성
Files.write(outputPath, sb.toString.getBytes(StandardCharsets.UTF_8));
sb.append("출력완료!: output.txt에 저장되었습니다.");
}
}
✅ 3. 차이점
구분 | try / catch / finally | Try / Success / Failure |
스타일 | 명령형(Imperative) | 함수형(Functional) |
에외 처리 | 실행 중 예외 던지고 잡음 | 예외를 값으로 래핑해 처리 |
프로그램 중단 | 예외를 잡지 않으면 중단 | Failure로 감싸져 중단 X |
주 사용처 | Java/C#과 유사한 방식이 필요할 때 | 안전한 함수형 프로그래 체이닝 작업 |
- 👉 간단한 예외만 잡겠다 -> try / catch / fianlly
- 👉 예외를 값처럼 안전하게 다루겠다 -> Try / Success / Failure
GitHub - Koras02/scala-bloging: https://thinky.tistory.com/category/Back-End/Scala
https://thinky.tistory.com/category/Back-End/Scala - Koras02/scala-bloging
github.com
728x90
LIST
'Back-End > Scala' 카테고리의 다른 글
[Scala] 8장 비동기 프로그래밍과 동시성 (0) | 2025.09.06 |
---|---|
[Scala] 7장 컬렉션과 데이터 처리 (0) | 2025.08.26 |
[Scala] 5장 - 패턴 매칭 & Case 클래스 (4) | 2025.08.14 |
[Scala] 4장 - 함수형 프로그램 (FP) 패러다임 (0) | 2025.08.12 |
[Scala] 3장 - 객체지향 프로그래밍(OOP) (1) | 2025.08.09 |