NullReferenceException,DivideByZeroException and InvalidCastException in C#
Tags: csharp
Published: 2020-05-27 10:22:23

In this post, I will introduce the NullReference,DivideByZeroException and InvalidCastException to you and provide the example of each Exception in sample words.it will help the developers to understand these exceptions and avoid them.


NullReferenceException:

The NullReference Exception occurs when try to access a member on type whose have a null value.

Example:
try{
            List<String> tiber = new List<String>();
            tiber = null;
            tiber.Add("hello");
        }
        catch(NullReferenceException exception)
        {
            Console.WriteLine("The variable is not instantiated.");
            Console.WriteLine("The following error detected: " + exception.GetType().ToString()+ " with message \"" + exception.Message+"\"");
        }

As the example above，the variable do not have a value to convert. The runtime system is in charge of throwing the exception.In theory, we don’t have to throw this exception but we need to throwing the exception if the reference type of variable do not instantiate by the programmer and we need to provides the massage “instantiate the reference type of the variable” to the user.To avoid the exception, the best way is to instantiate a variable or member after it has been declared.


DivideByZeroException：

This DivideByZeroException occurs when there is an attempt to divide an integral or decimal value by zero.

Example:

int T = 5000;
        int I = 0;
            try{
                int result = T / I;
            }
            catch(DivideByZeroException exception){
                Console.WriteLine(exception);
            }

The runtime system is in charge of throwing this exception. In theory, we need to throwing this exception when the exception due to user’ input. We should provide the error massage “attempt to divide the value by zero, please change it” to ask user for change value.Don’t need the parameter in this exception. This exception can be caught and handled. As the exception can be happened cause either the user’ input or programmer. We should pass it to the user if it is cause the user’ input. To avoid this exception, use the try – catch block to handle the user’ input can avoid the input(0) and checking programmer’s code carefully also can help us to avoid the Exception.

InvalidCastException：

This InvalidCastException occurs when invalid casting or explicit conversion.

Example:
bool Tiber = true;
            try
            {
                IConvertible A = Tiber;
                Char b = Convert.ToChar(Tiber);
                Console.WriteLine("Successfully！");
            }
            catch(InvalidCastException)
            {
                Console.WriteLine("Cannot convert a Boolean to a Char， please try again！");
            }
InvalidCastException will be throws when convert a Boolean value to Char value(the type is not in the same path of the type hierarchy).The runtime system is in charge of throwing this exception. In theory, we should to throwing this exceptions as it usually occurs because of user’s input. We need to provide error massage as “ Cannot convert a XXXX(type) to a XXXX(type” as the example above “ Cannot convert a Boolean to a Char”. The parameter can be two types of objects(variables). This exception can be caught and handled. If the exception occurs, we need to pass it to the user because this exceptions usually happened due to user’s input and we need to notices the user the exception happened cause their input. To avoid the exception, keep the type is in the same path of the type hierarchy and check the input will be good choice.

CONCLUSION:

This post NullReferenceException,DivideByZeroException and InvalidCastException. Please feel free to leave comment.Thank you for reading.