루비에서 시작, 구조 및 보장?
저는 최근에 루비에서 프로그래밍을 시작했고, 예외 처리를 보고 있습니다.
혹시나 해서요..ensure루비와 동등했습니다.finallyC#로? 내가 가져야 할 것:
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
rescue
#handle the error here
ensure
file.close unless file.nil?
end
아니면 제가 이걸 해야 하나요?
#store the file
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
file.close
rescue
#handle the error here
ensure
file.close unless file.nil?
end
한다ensure예외가 제기되지 않았더라도 무슨 일이 있어도 호출됩니까?
네.ensure코드가 항상 평가됩니다.그것이 그것이 불리는 이유입니다.ensure따라서 Java 및 C#의 경우와 동일합니다.finally.
의 일반적인 흐름begin/rescue/else/ensure/end다음과 같이 표시됩니다.
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
rescue SomeOtherException => some_other_variable
# code that deals with some other exception
else
# code that runs only if *no* exception was raised
ensure
# ensure that this code always runs, no matter what
# does not change the final value of the block
end
빼셔도 됩니다.rescue,ensure또는else예외 처리 코드에서 예외를 검사할 수 없는 경우 변수를 생략할 수도 있습니다. (글쎄요, 글로벌 예외 변수를 사용하여 마지막으로 발생한 예외에 액세스할 수는 있지만, 그건 좀 구식입니다.)그리고 예외 클래스를 생략할 수 있습니다. 이 경우 다음에서 상속되는 모든 예외가StandardError잡힐 것입니다. (이것이 모든 예외가 잡히는 것을 의미하는 것은 아닙니다. 왜냐하면 다음과 같은 예외가 있기 때문입니다.Exception하지만 아닙니다.StandardError대부분 다음과 같은 프로그램의 무결성을 손상시키는 매우 심각한 예외입니다.SystemStackError,NoMemoryError,SecurityError,NotImplementedError,LoadError,SyntaxError,ScriptError,Interrupt,SignalException또는SystemExit.)
일부 블록은 암시적 예외 블록을 형성합니다.예를 들어, 메서드 정의도 암묵적으로 예외 블록이므로 쓰기 대신
def foo
begin
# ...
rescue
# ...
end
end
당신은 그냥 씁니다.
def foo
# ...
rescue
# ...
end
또는
def foo
# ...
ensure
# ...
end
동일하게 적용됩니다.class정의 및module정의들.
하지만, 당신이 질문하는 구체적인 경우에는, 실제로 훨씬 더 좋은 관용구가 있습니다.일반적으로 마지막에 정리해야 하는 리소스를 사용하는 경우 모든 정리를 수행하는 메서드에 블록을 전달하여 이 작업을 수행합니다.그것은 a와 비슷합니다.usingRuby가 실제로 충분히 강력하기 때문에 Microsoft의 고위 성직자들이 산에서 내려와 당신을 위해 컴파일러를 친절하게 변경할 때까지 기다릴 필요가 없다는 것을 제외하고는 C#의 블록입니다.Ruby에서는 직접 구현할 수 있습니다.
# This is what you want to do:
File.open('myFile.txt', 'w') do |file|
file.puts content
end
# And this is how you might implement it:
def File.open(filename, mode='r', perm=nil, opt=nil)
yield filehandle = new(filename, mode, perm, opt)
ensure
filehandle&.close
end
그리고 당신이 알고 있는 것: 이것은 코어 라이브러리에서 이미 사용 가능합니다.File.open그러나 이것은 모든 종류의 자원 정리를 구현하기 위해 당신 자신의 코드에서도 사용할 수 있는 일반적인 패턴입니다.usingC#) 또는 거래 또는 기타 생각나는 모든 것.
리소스를 획득하고 해제하는 경우에만 프로그램의 다른 부분에 분산됩니다.그러나 예와 같이 현지화된 경우 이러한 리소스 블록을 쉽게 사용할 수 있습니다.
C에서 BTW: 현대의 C#에서,,usingRuby 스타일 리소스 블록을 직접 구현할 수 있기 때문에 실제로 불필요합니다.
class File
{
static T open<T>(string filename, string mode, Func<File, T> block)
{
var handle = new File(filename, mode);
try
{
return block(handle);
}
finally
{
handle.Dispose();
}
}
}
// Usage:
File.open("myFile.txt", "w", (file) =>
{
file.WriteLine(contents);
});
되더라도, 예가다제더라도기되시외▁f도라더제.rescue 션섹,ensure코드 실행이 다음 예외 처리기로 계속되기 전에 차단이 실행됩니다.예를 들어:
begin
raise "Error!!"
rescue
puts "test1"
raise # Reraise exception
ensure
puts "Ensure block"
end
인 닫이혀파일음확다인합사다니형용야해식블을록면있는려하지를 사용해야 합니다.File.open:
File.open("myFile.txt", "w") do |file|
begin
file << "#{content} \n"
rescue
#handle the error here
end
end
네.ensure모든 상황에서 호출됩니다.자세한 내용은 Programming Ruby 책의 "예외, 캐치, 던지기"를 참조하고 "확인"을 검색합니다.
이것이 우리가 필요한 이유입니다.ensure:
def hoge
begin
raise
rescue
raise # raise again
ensure
puts 'ensure' # will be executed
end
puts 'end of func' # never be executed
end
네.ensure항상실필않습다니지요가 필요하지 .file.close에 시대에begin블록으로 막다
참고로 테스트하는 좋은 방법은 다음과 같습니다.
begin
# Raise an error here
raise "Error!!"
rescue
#handle the error here
ensure
p "=========inside ensure block"
end
예외가 있을 때 "=========message sure block"이 인쇄되는지 테스트할 수 있습니다.하는 문장을 .ensure출력된 항목이 있는지 확인하여 문을 실행합니다.
네.ensure맘에 들다finally 블록이 실행되도록 보장합니다.이 기능은 오류 발생 시 파일 핸들을 닫거나 뮤텍스를 해제하는 등 중요한 리소스를 보호하는 데 매우 유용합니다.
언급URL : https://stackoverflow.com/questions/2191632/begin-rescue-and-ensure-in-ruby
'programing' 카테고리의 다른 글
| npm 설치로 devDependencies가 설치되지 않습니다. (0) | 2023.06.03 |
|---|---|
| 두 날짜 사이의 일 수 (0) | 2023.06.03 |
| 산술 연산으로 오버플로가 발생했습니다. (정수 추가) (0) | 2023.06.03 |
| jQuery는 요소에 속성이 있는지 확인하기 위해 특성을 가지고 있습니다. (0) | 2023.06.03 |
| Ruby 정규식의 \A \z와 ^ $ 간의 차이 (0) | 2023.06.03 |