Handling FormatException and NullReference date values in C#
In this article, you are going to learn how to fix the real-time invalid date (Ex: 29th October 2019) that leads to the FormatException issue.
Also, how to fix NullReferenceException when the user passed the value as null during runtime.
We will learn here in two different ways.
- Without Regex
- With Regex
Both approaches solve this FormatException but there is one catch with 1st approach (i.e., Tedious task: Adding the new date format for every new value) that you will fix easily using 2nd approach.
We are using one of the parsing methods from DateTime to fix this issue using two approaches.
Approach 1: Using Regex,
Parsing Success :
Handling Null value:
Using 1st approach (Null and FormattedException handles):
Note: All the above sample codes were tested with different inputs and all are working.
Thanks for reading this article I am hoping at this moment you understood the purpose of this article and knew the process of how to handle these exceptions.
— Happy coding :)