HiveBrain v1.2.0
Get Started
← Back to all entries
debugcsharpMinor

Handling null exception when having multiple variables

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingexceptionnullhavingmultiplewhenvariables

Problem

I have a lot of variables that I need to check for exceptions and output the empty field in case of a null returned value (I am reading a calender list from Sharepoint and my program is supposed to send email notifications if some of the conditions are met).

I surrounded my variables with a try-catch with a generic output "variable not found". Here is an example;

try
{
var name = item["Name"].ToString(); 
var dueDate= item["Due Date"].ToString();
.
.//more variables
.   
var Title= item["Title"].ToString();    
}
catch (Exception ex)
                        {
                            Console.WriteLine();
                            Console.WriteLine(ex.Message); //generic message for now
                            Console.WriteLine();
                        }


Is there is a way to handle this better? I know that going to each individual line and adding an exception is an option but it would save me a lot of time if I can just output something like the variable name.

Solution

Refactor into a method:

var name = this.GetVariable("Name"); 
var dueDate= this.GetVariable("Due Date");
.
.//more variables
.   
var Title= this.GetVariable("Title");    

private string GetVariable(string name)
{
    try
    {
        return item[name].ToString(); 
    }
    catch (Exception ex)
                        {
                            Console.WriteLine();
                            Console.WriteLine(name + " not found.");
                            Console.WriteLine();
                            return null;
                        }
}

Code Snippets

var name = this.GetVariable("Name"); 
var dueDate= this.GetVariable("Due Date");
.
.//more variables
.   
var Title= this.GetVariable("Title");    

private string GetVariable(string name)
{
    try
    {
        return item[name].ToString(); 
    }
    catch (Exception ex)
                        {
                            Console.WriteLine();
                            Console.WriteLine(name + " not found.");
                            Console.WriteLine();
                            return null;
                        }
}

Context

StackExchange Code Review Q#18862, answer score: 7

Revisions (0)

No revisions yet.