수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1695029
  • Today | 774
  • Yesterday | 606

3 Articles, Search for 'exception'

  1. 2007/07/27 Exception Handling in C#
  2. 2007/04/05 Exception class
  3. 2007/03/21 exception 클래스 확장하기
Programming/C#2007/07/27 09:14

Exception Handling in C#

As we all know, exception handling becomes a very handy tool for debugging an application. Rajesh will now explein how one should use Exceptions in C#.

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution. 

C# provides three keywords try, catch and finally to do exception handling. The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean up process.

The general form try-catch-finally in C# is shown below 

try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}

If any exception occurs inside the try block, the control transfers to the appropriate catch block and later to the finally block.  

But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks. 

If there is no exception occurred inside the try block, the control directly transfers to finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto. 

In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either Exception class or one of the standard derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException etc. 

Uncaught Exceptions

The following program will compile but will show an error during execution. The division by zero is a runtime anomaly and program terminates with an error message. Any uncaught exceptions in the current context propagate to a higher context and looks for an appropriate catch block to handle it. If it can’t find any suitable catch blocks, the default mechanism of the .NET runtime will terminate the execution of the entire program. 

//C#: Exception Handling
//Author:
rajeshvs@msn.com
   
using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 100/x;
                       Console.WriteLine(div);
           }
}

The modified form of the above program with exception handling mechanism is as follows. Here we are using the object of the standard exception class DivideByZeroException to handle the exception caused by division by zero. 

//C#: Exception Handling
//Author:
rajeshvs@msn.com
using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 0;
                       try
                       {
                                   div = 100/x;
                                   Console.WriteLine(“This line in not executed”);
                       }
                       catch(DivideByZeroException de)
                       {
                                   Console.WriteLine("Exception occured");
                                  
                      }
                       Console.WriteLine("Result is {0}",div);
           }
}

In the above case the program do not terminate unexpectedly. Instead the program control passes from the point where exception occurred inside the try block to the catch blocks. If it finds any suitable catch block, executes the statements inside that catch and continues with the normal execution of the program statements.

If a finally block is present, the code inside the finally block will get also be executed.  

//C#: Exception Handling
//Author:
rajeshvs@msn.com
  using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 0;
                       try
                       {
                                   div = 100/x;
                                   Console.WriteLine("Not executed line");
                       }
                       catch(DivideByZeroException de)
                       {
                                   Console.WriteLine("Exception occured");
                       }
                       finally
                       {
                                   Console.WriteLine("Finally Block");
                       }
                       Console.WriteLine("Result is {0}",div);
           }
}

Remember that in C#, the catch block is optional. The following program is perfectly legal in C#.

//C#: Exception Handling
//Author:
rajeshvs@msn.com
using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 0;
                       try
                       {
                                   div = 100/x;
                                   Console.WriteLine("Not executed line");
                       }
                       finally
                       {
                                   Console.WriteLine("Finally Block");
                       }
                       Console.WriteLine("Result is {0}",div);
           }
}
 

But in this case, since there is no exception handling catch block, the execution will get terminated. But before the termination of the program statements inside the finally block will get executed. In C#, a try block must be followed by either a catch or finally block 

Multiple Catch Blocks

A try block can throw multiple exceptions, which can handle by using multiple catch blocks. Remember that more specialized catch block should come before a generalized one. Otherwise the compiler will show a compilation error. 

//C#: Exception Handling: Multiple catch
//Author:
rajeshvs@msn.com
using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 0;
                       try
                       {
                                   div = 100/x;
                                   Console.WriteLine("Not executed line");
                       }
                       catch(DivideByZeroException de)
                       {
                                   Console.WriteLine("DivideByZeroException" );
                       }
                       catch(Exception ee)
                       {
                                   Console.WriteLine("Exception" );
                       }
                       finally
                       {
                                   Console.WriteLine("Finally Block");
                       }
                       Console.WriteLine("Result is {0}",div);
           }
}
 

Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block. Even we can use a catch block with an Exception type parameter to catch all exceptions happened inside the try block since in C#, all exceptions are directly or indirectly inherited from the Exception class.  

//C#: Exception Handling: Handling all exceptions
//Author:
rajeshvs@msn.com
using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 0;
                       try
                       {
                                   div = 100/x;
                                   Console.WriteLine("Not executed line");
                       }
                       catch
                       {
                                   Console.WriteLine("oException" );
                       }
                       Console.WriteLine("Result is {0}",div);
           }
}
 

The following program handles all exception with Exception object.

//C#: Exception Handling: Handling all exceptions
//Author:
rajeshvs@msn.com
using System;
class MyClient
{
           public static void Main()
           {
                       int x = 0;
                       int div = 0;
                       try
                       {
                                   div = 100/x;
                                   Console.WriteLine("Not executed line");
                       }
                       catch(Exception e)
                       {
                                   Console.WriteLine("oException" );
                       }
                       Console.WriteLine("Result is {0}",div);
           }
}

Throwing an Exception

In C#, it is possible to throw an exception programmatically. The ‘throw’ keyword is used for this purpose. The general form of throwing an exception is as follows.

throw exception_obj; 

For example the following statement throw an ArgumentException explicitly.

throw new ArgumentException(“Exception”); 

//C#: Exception Handling:
//Author:
rajeshvs@msn.com
using System;
class MyClient
{
           public static void Main()
           {
                       try
                       {
                                   throw new DivideByZeroException("Invalid Division");
                       }
                       catch(DivideByZeroException e)
                       {
                                   Console.WriteLine("Exception" );
                       }
                       Console.WriteLine("LAST STATEMENT");
           }
}
 

Re-throwing an Exception

The exceptions, which we caught inside a catch block, can re-throw to a higher context by using the keyword throw inside the catch block. The following program shows how to do this.  

//C#: Exception Handling: Handling all exceptions
//Author:
rajeshvs@msn.com
using System;
class MyClass
{
           public void Method()
           {
                       try
                       {
                                   int x = 0;
                                   int sum = 100/x;
                       }
                       catch(DivideByZeroException e)
                       {
                                   throw;
                       }
           }
}
class MyClient
{
           public static void Main()
           {
                       MyClass mc = new MyClass();
                       try
                       {
                                   mc.Method();
                       }
                       catch(Exception e)
                       {
                                   Console.WriteLine("Exception caught here" );
                       }
                       Console.WriteLine("LAST STATEMENT");
           }
}
 

Standard Exceptions
 
There are two types of exceptions: exceptions generated by an executing program and exceptions generated by the common language runtime. System.Exception is the base class for all exceptions in C#. Several exception classes inherit from this class including ApplicationException and SystemException. These two classes form the basis for most other runtime exceptions. Other exceptions that derive directly from System.Exception include IOException, WebException etc. 

The common language runtime throws SystemException. The ApplicationException is thrown by a user program rather than the runtime. The SystemException includes the ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch SystemExceptions nor is it good programming practice to throw SystemExceptions in our applications.

System.OutOfMemoryException

System.NullReferenceException

System.InvalidCastException

System.ArrayTypeMismatchException

System.IndexOutOfRangeException        

System.ArithmeticException

System.DevideByZeroException

System.OverFlowException

User-defined Exceptions

In C#, it is possible to create our own exception class. But Exception must be the ultimate base class for all exceptions in C#. So the user-defined exception classes must inherit from either Exception class or one of its standard derived classes.

//C#: Exception Handling: User defined exceptions
//Author:
rajeshvs@msn.com
using System;
class MyException : Exception
{
           public MyException(string str)
           {
                       Console.WriteLine("User defined exception");
           }
}
class MyClient
{
           public static void Main()
           {
                       try
                       {
                                   throw new MyException("RAJESH");
                       }
                       catch(Exception e)
                       {
                                   Console.WriteLine("Exception caught here" + e.ToString());
                       }
                       Console.WriteLine("LAST STATEMENT");
           }
}

Design Guidelines

Exceptions should be used to communicate exceptional conditions. Don’t use them to communicate events that are expected, such as reaching the end of a file. If there’s a good predefined exception in the System namespace that describes the exception condition-one that will make sense to the users of the class-use that one rather than defining a new exception class, and put specific information in the message.

Finally, if code catches an exception that it isn’t going to handle, consider whether it should wrap that exception with additional information before re-throwing it.

"C#" 카테고리의 다른 글
  • Introduction to Objects and Classes in C# (0)2007/07/27
  • Creational Patterns in C# (0)2007/07/27
  • Exception Handling in C# (0)2007/07/27
  • C# 키워드 목록 (0)2007/07/02
  • Event Handling in .NET Using C# (0)2007/06/26
2007/07/27 09:14 2007/07/27 09:14
Posted by webdizen
Tags C#, exception, Handing
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/3097

Leave your greetings.

[로그인][오픈아이디란?]

Programming/MFC2007/04/05 09:40

Exception class

원본 : http://www.sarangnamu.net/basic/basic_v ··· ory%3D33

The following table shows the predefined exceptions provided by MFC.

Exception class Meaning

CMemoryException

Out-of-memory

CFileException

File exception

CArchiveException

Archive/Serialization exception

CNotSupportedException

Response to request for unsupported service

CResourceException

Windows resource allocation exception

CDaoException

Database exceptions (DAO classes)

CDBException

Database exceptions (ODBC classes)

COleException

OLE exceptions

COleDispatchException

Dispatch (automation) exceptions

CUserException

Exception that alerts the user with a message box, then throws a generic CException

"MFC" 카테고리의 다른 글
  • ActiveX(MFC) 제작 TIP 또는 주의 사항 [1] (0)2007/04/24
  • XML using MFC (0)2007/04/05
  • Exception class (0)2007/04/05
  • Adding a Full Screen Feature to an MFC Application (0)2007/04/05
  • CreateDirectory 디렉토리, 폴더 (0)2007/04/05
2007/04/05 09:40 2007/04/05 09:40
Posted by webdizen
Tags exception
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/2789

Leave your greetings.

[로그인][오픈아이디란?]

Programming/C++2007/03/21 09:31

exception 클래스 확장하기

원본 : http://www.debuglab.com/knowledge/exceptionclass.html

1.요약

C++ 표준에는 exception이라는 상위 클래스가 있는데, MFC의 CException 과 같은 역할을 한다고 보시면 됩니다.

기본적은 exception 을 상속받는 클래스로서 bad_alloc, bad_cast, bad_typeid 등이 있는데, 이상하게도 Visual C++에는 bad_alloc 만 구현하지 않았습니다.

bad_alloc 은 new 가 실패했을때 던져지도록 약속된 Exception 클래스입니다.

여기서는 간단하기 bad_alloc을 구현해보겠습니다.


2.본문

우선 설명할 내용이 많지 않으므로 소스코드를 보여드리겠습니다.

#include <new.h> 

#include <exception> 

using namespace std; 



class bad_alloc : public exception 

{ 

public: 

    bad_alloc(const __exString& what_arg) : exception(what_arg) {} 

}; 



int NewHandler(size_t size) 

{ 

    throw bad_alloc("Operator new couldn't allocate memory"); 

    return 0; 

} 



int main(int argc, char* argv[]) 

{ 

    _set_new_handler(NewHandler); 

    _set_new_mode(1);  // use NewHandler for malloc as well 

    .... 

} 

이전에 보여드렸던 예제와 크게 다른 점은 없습니다.

프로그램이 시작할 때( 혹은 각 스레드 엔트리의 처음에서) new handler를 설치해야합니다.

그리고 _set_new_mode(1); 을 호출함으로써 malloc 역시 new 와 같이 동작하다록 만들 수 있습니다.

보너스로 Exception을 잡으실때(catch) 유의하실 점을 몇가지 적어보겠습니다.

1. Non-MFC C++ exception 이라면 reference 를 사용하시는 게 좋습니다.

이렇게 말이죠.

try { 

    throw MyException(); 

} 

catch(MyException& e) 

{ 

} 

이유는 간단합니다. 포인터를 사용한다면 객체를 동적으로 생성/소멸 시키는 루틴이 부가적으로 포함되어야 하기 때문에 안좋을테고, 그냥 MyException 을 사용한다면 추가적인 객체가 생성되고 복사생성자/소멸자가 추가적으로 호출될테니 비효율적이겠죠.

(참고적으로 dangling reference는 걱정하지 않으셔도 됩니다)


2. MFC exception 이라면 pointer를 사용해서 잡고, 반드시 Delete() 를 호출해주어야 합니다.

주의할 점으로는 절대 delete 를 사용해서 해제시켜서는 안됩니다.
exception이 static object인 경우도 있기 때문입니다.


3.예제



4.참고

Debuggin Windows Programs



- 2001.08.13 Smile Seo -

"C++" 카테고리의 다른 글
  • Advanced Breakpoint (0)2007/03/22
  • 동적으로 할당되는 메모리를 갖는 클래스를 위해서... (0)2007/03/21
  • exception 클래스 확장하기 (0)2007/03/21
  • operator new 와 operator delete 작성시 관례를... (0)2007/03/19
  • 메모리가 모자랄 경우에 대비한다 (0)2007/03/19
2007/03/21 09:31 2007/03/21 09:31
Posted by webdizen
Tags exception
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/2711

Leave your greetings.

[로그인][오픈아이디란?]

«Prev  1  Next»

RSS HanRSS
Blog Image
webdizen
이곳은 컴퓨터에 대해 연구하고, 공유하고, 소통하기 위한 연구실입니다. 개인적으로는 OLAP, Data Mining, Semantic Web, Data Modeling에 대해서 연구하고 있습니다.

Categories

전체 (3009)
Webdizen (141)
Life (6)
Diary (16)
Blog (9)
IDEA (2)
Travel (10)
Book (16)
Photo (7)
Movie (8)
Music (14)
Leisure Sports (10)
Funny (6)
Hardware (121)
Software (120)
Windows (5)
Unix & Linux (120)
Installation (5)
Kernel (10)
System (34)
Develop (22)
X-Window (0)
Applicaton (31)
Security (4)
Framework (2)
Hadoop (2)
Programming (804)
Algorithm & Data Structure (1)
Assembly (38)
UNIX/Linux C (95)
C++ (128)
STL (4)
Java (38)
Win32 API (92)
ATL/COM (44)
MFC (151)
.NET (26)
WCF/WPF (4)
C# (28)
Network Programming (17)
Database Programming (12)
OpenGL / DirectX (13)
Multimedia Programming (0)
Game Programming (21)
Parallel Distributed Progra... (0)
Reverse Engineering (0)
Debugging (9)
Python (1)
Ruby (1)
Ruby on Rails (1)
QT (4)
GTK (0)
JSP (0)
PHP (6)
ASP.NET (6)
ASP (2)
Development (28)
Useful Library (2)
Data Modeling (0)
Database (105)
Oracle (4)
MSSQL (41)
MySQL (2)
Data Warehouse (2)
Data Mining (4)
Network (66)
Web (79)
DHTML (4)
XHTML (1)
Javascript (1)
CSS (1)
AJAX (9)
XML (11)
Flex (1)
Silverlight (3)
Security (91)
DoS (1)
Kernel (10)
Scanning (3)
Sniffing (0)
Spoofing (4)
Overflow (28)
Web (11)
Shell (10)
Format String (14)
Window (2)
Embedded (70)
Multimedia (27)
Mobile (14)
Graphic (24)
Management (633)
Knowledge (581)
Hadoop (0)

Notice

  • 메타 블로그 사이트에 등록
  • 새해 맞이 블로그의 변화
  • 블로그 명칭 변경
  • 도메인(www.webdizen.net) 구...
  • TEXTCUBE 1.6.1로 업그레이드...

Tags

  • 데이타 웨어하우스
  • 까무스 XO
  • 메모리
  • 트위터
  • BMP
  • 실체화
  • Ultimate OSX
  • 디스크 복사
  • 뷰
  • 최적화
  • lynx
  • 복구
  • 썸씽 스페셜
  • 객체 비지향
  • 연구실
  • 프렌즈
  • memory 크기
  • VisualUnitTest++
  • 여행
  • 구급약

Recent Articles

  • 트위터(Twitter)의 시작!.
  • 청년 리더의 조건.
  • 애플의 타블렛 PC - 아이패드....
  • 미래의 인터페이스 - 육감 기....
  • 기초발성법 동영상 강좌.

Recent Comments

  • 경청... 너무나 중요한데.......
    webdizen 14:59
  • 학교 과제물중 쓰레드에 대하....
    장진혁 03/17
  • 관리자만 볼 수 있는 댓글입....
    비밀방문자 03/12
  • 상대방의 이야기를 열심히 경....
    DoNuts 03/03
  • 좋은글 잘 보고 갑니다..
    Und_hacker 01/08

Recent Trackbacks

  • printf,scanf를 이용한 형식....
    yundream의 프로그래밍 이야기 03/10
  • 파일 열기/저장하기 CFileDialog.
    은마군의 나태블록 2009
  • World IT Show 2008.
    상우 :: Oranzie's BLOG 2008
  • cvs서버 설치하기.
    3인3색 2008
  • 속속 공개되는 Google Chart....
    PHP와 Web 2.0 2007

Archive

  • 2010/02 (1)
  • 2010/01 (6)
  • 2009/12 (5)
  • 2009/09 (3)
  • 2009/08 (1)

Calendar

«   2010/03   »
일 월 화 수 목 금 토
  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 29 30 31      

Bookmarks

    • Administration
      • IIS.NET
      • NTFAQ
      • OS의 모든 것
      • 리눅스포털
    • Database
      • SQL Server Central
      • SQL Team
    • Development
      • .NET Heaven
      • ASP Alliance
      • ASP.NET 2.0
      • Bullog.net
      • C# Corner
      • C++ (C PlusPlus.com)
      • C++ Reference
      • CodeGuru
      • CodePlex
      • DebugLab
      • Dev Articles
      • Devpia
      • DotNet Junkies
      • DotNet Zone
      • Driver Online
      • GOSU.NET
      • HOONS 닷넷
      • Joinc 팀블로그
      • KOSR
      • MSDN Home Page
      • OSR Online
      • Sky.ph - 개발자 커뮤니...
      • TAEYO.NET
      • The Code Project
      • WindowsClient.net
      • 김상욱의 개발자 Side
      • 조인시 위키
    • Human Networks
      • belief21c's e-space
      • I think I can
      • Invisible Rover's Blog :D
      • Polarux - Linuxing
      • Rodman®
      • 까만 나비
      • 나를 가꾸는 시간.
      • 단녕
      • 상우 :: Oranzie's BLOG
    • Information Technology
      • Microsoft TechNet
      • 지디넷코리아 - 글로벌...
    • Security
      • FoundStone
      • milw0rm
      • NewOrder
      • OpenRCE
      • Phrack.org
      • Reverse Engineering b1...
      • Reverse Engineering Team
      • RootKit
      • SecurityFocus
      • SecurityXploded by Nag...
      • Wow Hacker
      • Zone-H
Textcube
Louice Studio Inc.
Powered by Textcube. Original designed by Tistory.