C# (C Sharp) - Errors and Exception Handling

C# (C Sharp) - Errors and Exception Handling 

Types of Errors 

In programming language errors can be divided into three categories as given below- 

  • Syntax Errors 

Syntax errors occur during development, when you make type mistake in code. For example, instead of writing while, you write WHILE then it will be a syntax error since C# is a case sensitive language. 

bool flag=true; 

WHILE (flag) //syntax error, since c# is case sensitive 

//TO DO: 

  • Runtime Errors (Exceptions) 

Runtime errors occur during execution of the program. These are also called exceptions. This can be caused due to improper user inputs, improper design logic or system errors. 

Exceptions can be handled by using try-catch blocks. 

int a = 5, b = 0; 

int result = a / b; // DivideByZeroException 

  • Logical Errors 

Logic errors occur when the program is written fine but it does not produce desired result. Logic errors are difficult to find because you need to know for sure that the result is wrong 

int a = 5, b = 6; 

double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0 

Exception Handling 

  • Exception handling is a mechanism to detect and handle run time errors. It is achieved by using Try-Catch
  • Finally blocks and throw keyword. 

Try block 

The try block encloses the statements that might throw an exception. 


// Statements that can cause exception. 

Catch block

Catch block handles any exception if one exists. 

catch(ExceptionType e) 

// Statements to handle exception. 

Finally block

The finally block can be used for doing any clean-up process like releasing unused resources even if an exception is thrown. For example, disposing database connection. 


// Statement to clean up. 

Throw keyword

This keyword is used to throw an exception explicitly. 

catch (Exception e) 

throw (e);