[Ruby] 8장 예외처리

1. 예외 처리

Ruby에서 예외 처리는 begin, rescue, ensure, else 블록을 사용해 예외처리를 할 수있습니다. 예외 처리를 통해 프로그램이 예상치 못한 오류로 중단되지 않도록 하고, 오류 발생 시 적절한 조치를 취할 수 있습니다. Ruby의 기본적인 예외 처리는 아래와 같습니다.

begin 
  # 예외가 발생할 수 있는 코드
  result = 10 / 0
rescue ZeroDivisionError => e
   # 예외 발생 시 실행될 코드
   puts "Error: #{e.message}"
ensure 
   # 예외 발생 여부와 상관 없이 실행되는 코드
   puts "Ensure block executed"
end
# Output: Error: divided by 0; 
#        Ensure block executed

2. 여러 예외 처리

여러 예외 처리를 통해 에러 종류에 따른 예외 처리를 할 수 있습니다.

# 여러 예외 처리 
begin 
   # 예외가 발생할 수 있는 코드
   result = 10 / 0
rescue ZeroDivisionError => e
  puts "ZeroDivisionError: #{e.message}"
rescue NoMethodError => e
  puts "NoMethodError: #{e.message}"
rescue StandardError => e
  puts "StandardError: #{e.message}"
end

3. 사용자 정의 예외

class를 통해 사용자 정의 예외 클래스를 생성할 수 있습니다.

class MyCustomError < StandardError; end

begin 
   raise MyCustomError, "This is my custom error message"
rescue MyCustomError => e
   puts "MyCustomError: #{e.message}" # Output: MyCustomError: This is my custom error message
end

4. 예외 처리의 실용적 사용 예

파일을 열고 처리하는 예외 처리를 구현할 수 있습니다.

begin
  file = File.open("non_existent_file.txt")
  # 파일 처리 코드
rescue Errno::ENOENT => e
  puts "File not found: #{e.message}"
ensure
  file.close if file # 파일일 열려 있을 경우 닫기
end

 

 

GitHub - set-up-init/ruby-tutorial-tistory: https://thinky.tistory.com/category/Back-End/Ruby

https://thinky.tistory.com/category/Back-End/Ruby. Contribute to set-up-init/ruby-tutorial-tistory development by creating an account on GitHub.

github.com

 

LIST