캐치 블록으로 돌아 오시겠습니까?
catch 블록에 return 문이있는 것이 잘못입니까? 대안은 무엇입니까?
즉 :
public bool SomeFunction()
{
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
return false;
}
}
catch 블록에서 정상적으로 돌아올 수 있습니다. 일반적으로 좋은 기능 코드입니다.
한 가지 대안은 반환 값을 임시 변수에 저장하는 것입니다.
public bool SomeFunction()
{
bool success = true;
try
{
//somecode
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
success = false;
}
return success;
}
그러나 개인적으로 나는 당신이 (하나의 catch-all catch 문으로) 작성한 방식이 더 읽기 쉽다는 것을 발견했습니다. 반면에 특정 예외를 예상하고 성공을 반환 할 경로가 여러 개있을 수있는 경우 ...
try
{
DoTheImportantThing();
DoTheOtherThingThatMightFailButWeDontCare();
}
catch (DontCareAboutItException ex)
{
log.Info(ex);
}
catch (Exception ex)
{
log.Error(ex);
return false;
}
return true;
그런 다음 가능한 한 끝까지 return 문을 밀어내는 것이 가장 좋습니다.
참고로 애플리케이션에 따라 예외를 사용자에게 표시하는 것보다 포착 한 예외를 로깅하는 것이 좋습니다. 기록 된 예외는 발생한 일에 대한 사용자의 기록보다 훨씬 더 신뢰할 수 있습니다.
try 블록에 이미 return 문이 있으면 함수 끝에 다른 return을 넣을 것입니다.
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
return false;
그리고 이것은 여러 예외를 처리해야하는 경우 여러 반환을 방지하기위한 것입니다.
반환 명령 후에 일부 코드가 실행될 수 있다는 점을 염두에 두십시오 (반환 값은 현금화 됨).
try
{
return;
}
catch(Exception ex)
{
return;
}
finally
{
//some code
}
public bool SomeFunction()
{
try
{
//somecode
return true;
}
catch(Exception ex)
{
MessageBox.Show(ex.message);
}
return false;
}
개인적으로 나는 catch-block 대신 메소드의 맨 아래에 return 문을 넣었습니다. 그러나 둘 다 괜찮습니다. 조직의 가독성 (주관적)과 지침에 관한 것입니다.
틀린 것은 아니지만 리소스를 사용한 경우 일반적으로 close 메서드를 두 번 호출하는 대신 finally 블록을 사용하여 닫습니다. 이 경우 finally 블록 뒤에 return 문을 사용하도록 선택할 수 있습니다.
네, 완벽하게 정상입니다.
Don't forget, that you can also use finally block to be executed after return.
Makes perfect sense to me for a function which returns true on success and false on failure. I hope there is nothing wrong with it - I do it all the time :)
The primary purpose of a catch block is to provide a place where one can proceed an exceptional situation which occurred in a try block. So you caught an exception, proceeded it... and returned from a method. If the caller method does not care about the exception, this is absolutely normal.
You can add a return
in the catch block. You explicitly know that your code will return and continue execution instead of halting at the catch block.
try{
//do something
}
catch{
//error handling
return;
}
Instead of having a lot of try-catch blocks in your code that can get confusing and just cause a mess in your code, it's better handle everything in your noe try catch and just check what the error returned was.
try{
//do something
}
catch (Exception as err){
if (err == "IOException"){
//handle exception
else if (err.indexOf("TypeError"){
//handle exception
}
}
These are two ways of checking what type the exception was so you can display a message accordingly. You can also just catch specific exceptions if you wanted so instead of Exception as err
you can do catch IOException, ...
ReferenceURL : https://stackoverflow.com/questions/2690065/return-in-catch-block
'developer tip' 카테고리의 다른 글
Django의 ModelForm unique_together 유효성 검사 (0) | 2020.12.25 |
---|---|
Django의 계단식 삭제 동작을 재정의하는 옵션은 무엇입니까? (0) | 2020.12.25 |
Java에서 RESTful API를 만드는 방법을 배우는 데 가장 좋은 소스는 무엇입니까? (0) | 2020.12.25 |
다른 개체에 전달 될 때 IDisposable 개체에 대해 Dispose를 호출해야하는 사람은 누구입니까? (0) | 2020.12.25 |
C ++에서 typename T를 문자열로 변환하는 방법 (0) | 2020.12.25 |