In this article we will focus on Exception Handling, clarify our knowledge on different type of Exceptions, and also identify difference between Exception and Error.
Short Overview:
Error:
- Error means system doesn’t handle.
- Stop the application being executed with errors.
- Cause while syntax error, may occur while writing code.
Exception:
- Abnormal things happen cause Exception.
- Interrupts the application execution.
- Cause while application logic fails, something exceptional.
Details:
Types of Errors:
- Compile Errors
- Run-Time Errors
- Logical Errors
Compile Error:
Also known as Build Error. As we know C# is a case sensitive language. A compile error may cause due to a misuse of the C# language (syntax error). Appear while we write code. We can fix them easily in the coding environment as soon as they occur.
Errors at compile time:
- Syntax errors
- Type Checking errors
- Compiler crashes
Example:
namespace CompileError { class Program { static void Main(string[] args) { int x = 1, y = 0, result = 0; result = x / y //cause compile error Console.WriteLine(result); Console.Read(); } } }
Generate error while compiling the project.
OUTPUT: ; expected
Note:
- It will only accept programs that have the correct syntax.
- This ensure that the program is correct, can be compiled/build.
- No program will be executed with errors.
- Can’t be handled.
Run-Time Error:
A run-time error may cause if something unexpected happened.
Errors at run-time:
- Division by zero
- Unexpected user inputs.
- Differencing a null pointer
- Running out of memory
- Trying to open a file that is corrupted or no existence.
Now if we consider the same example with the corrected form of syntax. In the compilation there will be no error but an exception is caught while we execute the program, this will stops running the program. An unexpected result is generated where 1 divided by 0 is infinity.
Another example is shown while we are trying to parse a string to int, this will cause a runtime error while the code is correct at compile time.
Example:
namespace RuntimeError { class Program { static void Main(string[] args) { int result = 0; //int x = 1, y = 0; //result = x / y; //no compile error //Console.WriteLine(result); int a = 1, b = int.Parse("abc"); result = a / b; //no compile error Console.WriteLine(result); Console.Read(); } } }
Generate error while executing the project.
OUTPUT:
An unhandled exception of type ‘System.FormatException’ occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Note:
- Run-time errors occur when the program is executed.
- A runtime errors are called exceptions.
- Run time errors are not detected by the compiler, because the code is syntactically correct.
- Can be handled.
Handling Exceptions:
There are exceptions to every rule. In our application sometimes things go wrong while fail to fulfil the rule, then something happened unexpectedly during the execution of a program.
The C# language’s exception handling features gives us some options to deal with any unexpected or exceptional situations that occur when a program is executing.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
Syntax:
try{//…..}
catch( Exception ex_1 ){ //…..}
catch(Exception ex_2 ){ //…..}
catch(Exception ex_N ){ //…..}
finally{ //…..}
try: A try block identifies a block of code for which particular exceptions is activated.
catch: This is used to catch exceptions. A program catches an exception with an exception handler at the place in a program where we want to handle the problem. The catch keyword indicates the catching of an exception.
finally: The code enclosed by the finally block is executed in a program, whether an exception is thrown or not thrown.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Example Try Catch Finally:
In the below program, the code inside the catch block is executed followed by the code in finally block.
This is how the Exception is handled by this program.
namespace TryCatch { class Program { static void Main(string[] args) { long result = 0; try { int x = 1, y = 0; result = x / y; //no compile error } catch (Exception ex) { Console.WriteLine("Exception 1: {0}", ex); } finally { Console.WriteLine("Result: {0}", result); } try { int a = 1, b = int.Parse("abc"); result = a / b; //no compile error } catch (Exception ex) { Console.WriteLine("Exception 2: {0}", ex); } finally { Console.WriteLine("Result: {0}", result); } Console.Read(); } } }
Example Throw & Throw ex:
Below example uses “exception rethrow” in two different ways.
- The first segment performs silent rethrow, using the keyword “throw”.
- The second rethrows the exception object received through the catch block parameter.
- The first segment is best way to rethrow because it maintains all the information about the real origin of the exception.
namespace ThrowReThrow { class Program { private static void ThrowException1() { try { int a = 1, b = int.Parse("abc"); int result = a / b; //no compile error } catch { throw; } } private static void ThrowException2() { try { int a = 1, b = int.Parse("abc"); int result = a / b; //no compile error } catch (Exception ex) { throw ex; } } static void Main(string[] args) { try { ThrowException1(); } catch (Exception ex) { Console.WriteLine("Exception 1:"); Console.WriteLine(ex); Console.Read(); } try { ThrowException2(); } catch (Exception ex) { Console.WriteLine("Exception 2:"); Console.WriteLine(ex); Console.Read(); } } } }
Note:
- Exceptions are types that all ultimately derive from System.Exception.
- Do not catch an exception unless you can handle it and leave the application in a known state.
Logical Error:
A logic error is a bug in a program that causes it to operate incorrectly, but not to terminate abnormally (or crash). The code does not produce desired result.
Example:
In the below example the expected output was full name, by mistake I have forgot to assign the value of last name, now this will show only the first name as full name.
namespace LogicErrors { class Program { static void Main(string[] args) { string FirstName = "Shashangka", LastName = ""; string fullName = FirstName + LastName; Console.WriteLine(fullName); Console.Read(); } } }
Note:
- Logic errors are the hardest to find and fix.
- Does not produce desired result.