
예외
프로그램이 실행되는 동안에 다양한 종류의 에러가 발생하는데 , 실행시간에 발생하는 에러를 예외라고 함.
예외처리기
에외도 하나의 객체로 취급하여 관련된 메시지를 스트링형태로 담어 전달함.
예외발생
예외가 발생하는 경우는 시스템에 의해 묵시적으로 일어나는 경우와 프로그래머가 명시적으로 발생시키는 방법이 잇다.
의도를 가질 때는 throw를 사용한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using System; class UserException : ApplicationException { } class UserExThrowApp { static void Method() { throw new UserException(); // 상위 생성자 호출됨. } static void Main(string[] args) { try { Console.WriteLine("1"); Method(); Console.WriteLine("2"); } catch(UserException) { Console.WriteLine("user-defined Exception"); } } } | cs |
try - catch - finally 문
try{ 예외 검사 }
catch{ 예외 처리기 }
catch { 예외 처리 2}
finally { 반드시 실행 }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; class FinallyClauseApp { static int count = 0; public static void Main(string[] args) { while (true) { try { if(++count == 1) { throw new Exception(); } if(count == 3) { break; } // 여기서 빠져나가도 finally 실행함. Console.WriteLine(count + ") No exception"); } catch (Exception) { Console.WriteLine(count + ") Exception thrown"); } finally { //fianlly는 try문에서 실행이되든 , catch문으로 가든 실행이 된다. Console.WriteLine(count + ") in finally clause "); } } Console.WriteLine("Main program ends"); } } | cs |
실행결과
1) Exception thrown
1) in finally clause
2) No exception
2) in finally clause
3) in finally clause
Main program ends
finally는 Exception이 실행이되든 안되든 실행함.
들어온 이상 break문으로 빠져나가도 실행함
'C# > C# Concept' 카테고리의 다른 글
[C#] override new (0) | 2018.05.03 |
---|---|
[C#] 연산자 오버로딩 (0) | 2018.05.02 |
[C#] 표준 애트리뷰트 ( conditional, Obsolete, 사용자정의 attribute) (0) | 2018.04.30 |
[C#] 업캐스팅 다운 캐스팅 (0) | 2018.04.30 |
[C#] 5단원 셤공부용 정리 (0) | 2018.04.20 |