프레임워크/Spring

[Spring] 예외 처리시 Throws vs try-cat-finally

pythaac 2022. 1. 18. 23:56

  예외처리를 하는 방법으로 Throws와 try-cat 두 가지 방법이 있는데, 어떤 방식으로 예외처리를 사용하는 것이 좋을지 찾아보게 되었습니다. 어떤 예외처리를 사용할지에 대해 간단하게 다음 2가지 기준이 있었습니다.

  1. catch문에서 유의미한 처리를 할 수 있는 경우만 try-catch 사용
  2. input parameter로 인한 오류의 경우 throws Exception 사용

 

CrudRepository Exception

  CrudRepository를 사용할 때는 따로 exception을 확인할 필요가 없는게 DataAccessException에 대해 built-in되어 있다고 합니다.

  1. NonTransientDataAccessException
    - DB에 존재하지 않는 id의 접근과 같이, 예외 원인이 정정되지 않는 같은 operation의 retry 경우
  2. RecoverableDataAccessException
    - 1번과 반대로, 실패한 이전 operation이 recovery로 성공이 가능한 경우
  3. ScriptException
    - SQL 관련 예외 경우
  4. TransientDataAccessException
    - timeout과 같이, 별도의 처리 없이 recovery가 가능한 경우

 

try-catch-finally에서 finally의 실행여부

  참고로, try-catch-finally에서 try 또는 catch에서 return을 만나더라도 finally문은 무조건 실행됩니다. finally는 객체 메모리를 정리할 때 최종적으로 처리할 무조건 처리할 동작을 넣기 위해 만들어진 것으로 알고 있습니다.

 

https://stackoverflow.com/questions/3203297/throws-or-try-catch

 

Throws or try-catch

What is the general rule of thumb when deciding whether to add a throws clause to a method or using a try-catch? From what I've read myself, the throws should be used when the caller has broken th...

stackoverflow.com

https://stackoverflow.com/questions/23325413/spring-crudrepository-exceptions

 

Spring CrudRepository exceptions

I have this Spring Data CrudRepository which handles the CRUD operations on a DB. @Repository public interface IUserRepository extends CrudRepository<User, String> { } User is the Entity of a

stackoverflow.com