Error & Exception

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:

  1. Error means system doesn’t handle.
  2. Stop the application being executed with errors.
  3. Cause while syntax error, may occur while writing code.

Exception:

  1. Abnormal things happen cause Exception.
  2. Interrupts the application execution.
  3. Cause while application logic fails, something exceptional.

Details:

Types of Errors:

  1. Compile Errors
  2. Run-Time Errors
  3. 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:

  1. Syntax errors
  2. Type Checking errors
  3. 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:

  1. It will only accept programs that have the correct syntax.
  2. This ensure that the program is correct, can be compiled/build.
  3. No program will be executed with errors.
  4. Can’t be handled.

Run-Time Error:

A run-time error may cause if something unexpected happened.

Errors at run-time:

  1. Division by zero
  2. Unexpected user inputs.
  3. Differencing a null pointer
  4. Running out of memory
  5. 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:

  1. Run-time errors occur when the program is executed.
  2. A runtime errors are called exceptions.
  3. Run time errors are not detected by the compiler, because the code is syntactically correct.
  4. 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.

  1. The first segment performs silent rethrow, using the keyword “throw”.
  2. The second rethrows the exception object received through the catch block parameter.
  3. 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:

  1. Exceptions are types that all ultimately derive from System.Exception.
  2. 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:

  1. Logic errors are the hardest to find and fix.
  2. Does not produce desired result.

Author:

Since March 2011, have 8+ years of professional experience on software development, currently working as Senior Software Engineer at s3 Innovate Pte Ltd.

Leave a Reply