데이터베이스에 쓰는 내 메서드에서 아래 코드와 같이 오류를 처리합니다. catch (DbUpdateException ex)
에서 예외를 다시 던져서 마지막 catch (Exception ex)
에 잡으려고합니다.동일한 메서드에서 예외를 throw하고 catch하십시오.
그렇게 할 수 있습니까? 아래 코드는 그렇게하지 않습니다.
using (Entities context = new Entities())
{
try
{
context.Office.Add(office);
retVal = context.SaveChanges();
}
catch (DbUpdateException ex)
{
SqlException innerException = ex.GetBaseException() as SqlException;
if (innerException != null && innerException.Number == (int)SQLErrorCode.DUPLICATE_UNIQUE_CONSTRAINT)
{
throw
new Exception("Error ocurred");
}
//This is momenty where exception is thrown.
else
{
throw ex;
}
}
catch (Exception ex)
{
throw
new Exception("Error");
}
}
. 스택 추적은 계속 재설정됩니다. –
[제발 흐름 제어에 대한 예외를 사용하지 마십시오] (http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control) –
왜 그걸 원하니? 마지막 catch는 모든 예외 세부 사항을 숨기므로 디버깅 및 유지 관리가 더 어려워집니다. 예외를 처리하지 않으려는 경우 거품을 버리십시오. – Oscar