자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Scala] 6장 - 에러 처리

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