System argumentnullexception как исправить

A System.ArgumentNullException occurs when an invalid argument is passed to a method in C#. In this case, it refers to the passing of a null object when the method expects a non-null object or a value. Similar to other exceptions raised as a result of arguments, System.ArgumentNullException is not generally raised by the .NET framework itself or the Common Language Runtime (CLR). Instead, it is thrown by an application or a library as an indication of improper null arguments.

Syntax of ArgumentNullException

Similar to any class or method, exceptions also have their own syntax.

Below is the syntax for ArgumentNullException:

public class ArgumentNullException : ArgumentException

The ArgumentNullException comes under the class of ArgumentException, which is inherited from the SystemException class. The SystemException class is in turn inherited from the Exception class, which is inherited from the Object class.

Object -> Exception -> SystemException -> IOException -> FileNotFoundException

When does the ArgumentNullException occur in C#?

Generally, there are two major circumstances when an ArgumentNullException is thrown, both of which reflect developer errors:

  • An object returned from a method call is then passed as an argument to a second method, but the value of the original returned object is null. To prevent the error, check for a return value that is null and call the second method only if the return value is not null.
  • An uninstantiated object is passed to a method. To prevent the error, instantiate the object.

Example One: Working with an Inbuilt Function like Parse()

In the below code, we are trying to parse and convert a string value to an integer value, assuming that the string is valid and contains only numbers.

class Program
    {
        static void Main(string[] args)
        {

            string id = null;
            int ans = int.Parse(id); // error is thrown

        }
    }

Output of Example 1

We can see that StringToNumber is causing the error because its parameter should not be null.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: String
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at ConsoleApp1.Program.Main(String[] args) in C:ConsoleApp1ConsoleApp1Program.cs:line 50

Example Two: Dealing with Custom Classes

In the below code we have created a class Books, two private strings, author and title, and used them for the public properties of Author and Title respectively. Then we wrote custom Title.set () and Author.set () functions that checked whether or not the passed argument value was null.

If true, we throw in a new System.ArgumentNullException instead of passing the entire message, as is frequently the case, System.ArgumentNullException expects just the name of the argument, which should not be null.

namespace ConsoleApp1
{

    public class Books
    {
        private string authors;
        private string titles;
        public string Author
        {
            get { return authors; }
            set {

                if (value is null)

                    throw new System.ArgumentNullException("Author");

                authors = value; 
                }
        }

        public string Title
        {
            get { return titles; }
            set {
                if (value is null)

                    throw new System.ArgumentNullException("Title");
                titles = value; }

        }

        public Books(string title, string author)
        {
            Author = author;
            Title = title;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            var obj = new Books("Harry potter", null);

        }
    }
}

Output of Example Two

When the above code is run we get the following output:

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: Author
   at ConsoleApp1.Books.set_Author(String value) in C:ConsoleApp1ConsoleApp1Program.cs:line 21
   at ConsoleApp1.Books..ctor(String title, String author) in C:ConsoleApp1ConsoleApp1Program.cs:line 39
   at ConsoleApp1.Program.Main(String[] args) in C:ConsoleApp1ConsoleApp1Program.cs:line 49

The parameter Author is causing this exception as its value should not be null.

How to Handle ArgumentNullException in C#

Now let’s see how to debug and handle this exception in C#. The best approach is to use try-catch block and perform a simple check before passing the values. Let’s see how to fix both examples discussed earlier.

How to Fix Example One:

On observing the first few lines of the output from the bottom to the top, it is quite evident that when parsing a string to convert the string to a number, System.ArgumentNullException occurs as the argument of int.Parse()cannot be null.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
Parameter name: String
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)

Working Code:

class Program
    {
        static void Main(string[] args)
        {

            try
            {
                string id = null;

                if (id is null)
                {
                    throw new ArgumentNullException("Id Argument cannot be null");
                }
                else {
                    int ans = int.Parse(id);
                }

            }catch (ArgumentNullException e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }

Output:

Value cannot be null.
Parameter name: Id Argument cannot be null

How to Fix Example Two:

Implement a try-catch block in this case because the value is being checked in the set() method.

Working Code:

namespace ConsoleApp1
{

    public class Books
    {
        private string authors;
        private string titles;
        public string Author
        {
            get { return authors; }
            set {

                if (value is null)

                    throw new System.ArgumentNullException("Author");

                authors = value; }
        }

        public string Title
        {
            get { return titles; }
            set {
                if (value is null)

                    throw new System.ArgumentNullException("Title");
                titles = value; }

        }

        public Books(string title, string author)
        {
            Author = author;
            Title = title;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            try
            {

                var obj = new Books("Harry potter", null);
            }catch(ArgumentNullException e)
            {
                Console.WriteLine(e.Message);
            }

        }
    }
}

Output:

Value cannot be null.
Parameter name: Author

Avoiding ArgumentNullExceptions

To summarize, an ArgumentNullException comes from ArgumentExceptions when an invalid argument is passed to a method. In this case, it refers to passing a null object when the method expects a non-null object or a value. Furthermore, whenever dealing with strings, it’s always good practice to perform a null check and then pass any arguments.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing C# errors easier than ever. Sign Up Today!

I’m creating a Unit Test for my CRUD and receiving this kind of error in my Delete test method:

System.ArgumentNullException: Value cannot be null.

I checked and found out that whenever I’m running the test, the contents under my userID was already deleted but receiving a «Failed» status in my Test Results bar. Can anyone help me resolve my issue?

Error Message: Test method TestProject1.UserTest.Delete threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: entity

Here’s my code:

[TestMethod]
public void Delete()
{
taskModelContainer db = new taskModelContainer();

int userID = 7;

TaskMgr.Models.User UserEntity = new TaskMgr.Models.User();

UserEntity.userID = userID;

UserController User = new UserController();

ActionResult result = User.DeleteConfirmed(UserEntity.userID);
int id = Convert.ToInt32(User.ViewBag.id);
User Users = db.Users.Single(e => e.userID == id);


Assert.IsNull(Users.userID);

}

Controller:

[HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(int id)
    {
        User user = db.Users.Find(id);
        db.Users.Remove(user);
        db.SaveChanges();
        var qry = from e in db.Users orderby e.userID descending select e.userID;
        int eID = qry.First();
        ViewBag.id = user.userID;
        return RedirectToAction("Index");
    }

It stops at this line of the controller: db.Users.Remove(user);

Jun 7, 2017 9:00:44 AM |
.NET Exception Handling — System.ArgumentNullException

A look at the System.ArgumentNullException in .NET, including some basic C# code examples and illustration of copy constructor best practices.

Making our way through our .NET Exception Handling series, today we’ll take a closer look at the System.ArgumentNullException. Similar to the System.ArgumentException that we covered in another article the System.ArgumentNullException is the result of passing an invalid argument to a method — in this case, passing a null object when the method requires a non-null value.

Similar to other argument exception types the System.ArgumentNullException isn’t typically raised by the .NET Framework library itself or the CLR, but is usually thrown by the library or application as an indication of improper null arguments.

In this article we’ll explore the System.ArgumentNullException in more detail including where it resides in the .NET exception hierarchy. We’ll also take a look at some functional sample C# code to illustrate how System.ArgumentNullException should typically be thrown in your own projects, so let’s get going!

The Technical Rundown

  • All .NET exceptions are derived classes of the System.Exception base class, or derived from another inherited class therein.
  • System.SystemException is inherited from the System.Exception class.
  • System.ArgumentException inherits directly from System.SystemException.
  • Finally, System.ArgumentNullException inherits directly from System.ArgumentException.

When Should You Use It?

As mentioned in the introduction the occurrence of a System.ArgumentNullException typically means the developer of the module or library you’re using wanted to ensure that a non-null object was passed to the method in question that caused the exception. Similarly, when writing your own code it’s considered a best practice to always validate the passed arguments of your methods to ensure no passed values are null and, therefore, might break your code or lead to unintended consequences. For more information on the code quality rules that apply see CA1062: Validate arguments of public methods.

In practice this means that throwing System.ArgumentNullExceptions should be performed within virtually every method you write that should not accept a null argument. To illustrate we have a simple example of our custom Book class with a few properties of Author and Title:

public class Book
{
private string _author;
private string _title;

public string Author
{
get
{
return _author;
}
set
{
// Check if value is null.
if (value is null)
// Throw a new ArgumentNullException with "Author" parameter name.
throw new System.ArgumentNullException("Author");
_author = value;
}
}

public string Title
{
get
{
return _title;
}
set
{
// Check if value is null.
if (value is null)
// Throw a new ArgumentNullException with "Title" parameter name.
throw new System.ArgumentNullException("Title");
_title = value;
}
}

public Book(string title, string author)
{
Author = author;
Title = title;
}
}

We’ve opted to create the private _author and _title fields and then use them for our public properties of Authorand Title, respectively. This allows us to create a custom Author.set() and Title.set() methods in which we check if the passed value is null. In such cases we throw a new System.ArgumentNullException and, rather than passing in a full error message as is often the case, System.ArgumentNullException expects just the name of the parameter that cannot be null.

To illustrate this behavior we have two basic example methods:

private static void ValidExample()
{
try
{
// Instantiate book with valid Title and Author arguments.
var book = new Book("The Stand", "Stephen King");
// Output book results.
Logging.Log(book);
}
catch (System.ArgumentNullException e)
{
Logging.Log(e);
}
}

private static void InvalidExample()
{
try
{
// Instantiate book with valid Title but invalid (null) Author argument.
var book = new Book("The Stand", null);
// Output book results.
Logging.Log(book);
}
catch (System.ArgumentNullException e)
{
Logging.Log(e);
}
}

As you can see the ValidExample() method creates a new Book instance where both the Title and Author parameters are provided so no exceptions are thrown and the output shows us our book object as expected:

{Airbrake.ArgumentNullException.Book}
Author: "Stephen King"
Title: "The Stand"

On the other hand our InvalidExample() method passed null as the second Author parameter, which is caught by our null check and throws a new System.ArgumentNullException our way:

[EXPECTED] System.ArgumentNullException: Value cannot be null.
Parameter name: Author

Using copy constructors is another area to be careful of and to potentially throw System.ArgumentNullExceptions within. For example, here we’ve modified our Book class slightly to include a copy constructor with a single Book parameter that copies the Author and Title properties. In addition, to illustrate the difference between regular instances and copies, we’ve also added the IsCopy property and set it to true within the copy constructor method only:

public class Book
{
// ...

public bool IsCopy { get; set; }

public Book(string title, string author)
{
Author = author;
Title = title;
}

// Improper since passed Book parameter could be null.
public Book(Book book)
: this(book.Title, book.Author)
{
// Specify that this is a copy.
IsCopy = true;
}
}

This presents a potential problem which we’ll illustrate using two more example methods:

private static void ValidCopyExample()
{
try
{
// Instantiate book with valid Title and Author arguments.
var book = new Book("The Stand", "Stephen King");
var copy = new Book(book);
// Output copy results.
Logging.Log(copy);
}
catch (System.ArgumentNullException e)
{
Logging.Log(e);
}
}

private static void InvalidCopyExample()
{
try
{
// Instantiate book with valid Title and Author arguments.
var copy = new Book(null);
// Output copy results.
Logging.Log(copy);
}
catch (System.ArgumentNullException e)
{
Logging.Log(e);
}
}

ValidCopyExample() works just fine because we first create a base Book instance then copy that using our copy constructor to create the copy instance, which we then output to our log. The result is a Book instance with the IsCopy property equal to true:

{Airbrake.ArgumentNullException.Book}
IsCopy: True
Author: "Stephen King"
Title: "The Stand"

However, we run into trouble in the InvalidCopyExample() method when trying to pass a null object to our copy constructor (remember that C# knows we’re using that copy constructor since we’ve only passed one argument and the other constructor [Book(string title, string author)] requires two arguments). This actually throws a System.NullReferenceException when we hit the : this(book.Title, book.Author) line since our code cannot reference properties of the null book object that we passed.

The solution is to use an intermediary null checking method on our passed instance before we actually attempt to set the properties. Here we’ve modified our copy constructor to use the newly added NullValidator() method:

// Validates for non-null book parameter before copying.
public Book(Book book)
// Use method-chaining to call the Title and Author properties
// on the passed-through book instance, if valid.
: this(NullValidator(book).Title,
NullValidator(book).Author)
{
// Specify that this is a copy.
IsCopy = true;
}

// Validate for non-null copy construction.
private static Book NullValidator(Book book)
{
if (book is null)
throw new System.ArgumentNullException("book");
// If book isn't null then return.
return book;
}

With these changes we can now invoke our InvalidCopyExample() method again and produce the System.ArgumentNullException that we expect because our passed book argument is still null:

[EXPECTED] System.ArgumentNullException: Value cannot be null.
Parameter name: book

To get the most out of your own applications and to fully manage any and all .NET Exceptions, check out the Airbrake .NET Bug Handler, offering real-time alerts and instantaneous insight into what went wrong with your .NET code, along with built-in support for a variety of popular development integrations including: JIRA, GitHub, Bitbucket, and much more.

1 / 1 / 0

Регистрация: 20.01.2019

Сообщений: 18

1

.NET 4.x

17.11.2021, 11:04. Показов 5216. Ответов 6


Студворк — интернет-сервис помощи студентам

Здравствуйте. В ноябре 20-го года делал программу-тест с простым графическим интерфейсом, считывающую вопросы из txt-файла (полный проект во вложении). Точно помню, что она работала, зачёт по ней сдан. Сейчас она мне понадобилась для другой работы, но при решении 7-го вопроса теста из 10 Visual Studio выдаёт ошибку: System.ArgumentNullException: «Значение не может быть неопределенным. Имя параметра: String» (скрин во вложениях).
Помогите, пожалуйста, разобраться, что не так и вернуть проект в рабочее состояние, заранее спасибо.

Миниатюры

Ошибка: System.ArgumentNullException: "Значение не может быть неопределенным. Имя параметра: String"
 



0



2728 / 1644 / 870

Регистрация: 14.04.2015

Сообщений: 5,611

17.11.2021, 11:43

2

Лучший ответ Сообщение было отмечено metalphoenix как решение

Решение

metalphoenix, лишние пустые строки из файла уберите



1



1 / 1 / 0

Регистрация: 20.01.2019

Сообщений: 18

17.11.2021, 12:18

 [ТС]

3

AndreyVorobey, вы имеете в виду пустые строки в конце текстового файла с вопросами «t.txt»? Убрал, не помогло.

Добавлено через 5 минут
Ругается схожей ошибкой, только уже на другое место



0



1 / 1 / 0

Регистрация: 20.01.2019

Сообщений: 18

17.11.2021, 12:19

 [ТС]

4

Скрин

Миниатюры

Ошибка: System.ArgumentNullException: "Значение не может быть неопределенным. Имя параметра: String"
 



0



1 / 1 / 0

Регистрация: 20.01.2019

Сообщений: 18

17.11.2021, 12:26

 [ТС]

5

AndreyVorobey, Благодарю. Оказывается, в каталоге был дубль текстового файла, строки надо было убирать в нём.



0



2728 / 1644 / 870

Регистрация: 14.04.2015

Сообщений: 5,611

17.11.2021, 12:28

6

metalphoenix, ну так это не дубль, а тот файл, с которого считываются данные. нет? в первом файле было 10 вопросов, а во втором 7, и на нем ошибка была. мне казалось, это и так было понятно



0



1 / 1 / 0

Регистрация: 20.01.2019

Сообщений: 18

17.11.2021, 12:33

 [ТС]

7

AndreyVorobey, да, именно так. Пустые строки были в обоих. Видимо, файл с 10 вопросами я ранее сделал как резерв для изменения вопросов в будущем, а сейчас не сразу понял, что данные считываются не с него, а из того, в котором 7 вопросов. Ещё раз благодарю вас за оперативную помощь, хорошего вам дня)



0



The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.

We haven’t written anything about avoiding this exception yet. Got a good tip on how to avoid throwing System.ArgumentNullException? Feel free to reach out through the support widget in the lower right corner with your suggestions.

It seams all you want to do is filter your context.Books by some criteria.

IEnumerable<Book> books = context.Books.Where(b => someConditions);

If you still need the empty IEnumerable you can just call Enumerable.Empty():

IEnumerable<Book> books = Enumerable.Empty<Book>();

I’m answering my own question.

I tried adding following in my web.config

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

Also decorated my Service with following attribute

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]    
public class CalculatorService : ICalculatorSession    
{
    // Implement calculator service methods
 }

Still no use.
Then I got the solution here by which you can use Elmah without HTTPContext. i.e. log errors by writing

Elmah.ErrorLog.GetDefault(null).Log(new Error(ex));

instead of

Elmah.ErrorSignal.FromCurrentContext().Raise(error);

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! — but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Thanks everyone, here is my ErrorHelper class I came up with to manually log errors on websites and in WCF services, windows services, etc:

    public static class ErrorHelper
{
    /// <summary>
    /// Manually log an exception to Elmah.  This is very useful for the agents that try/catch all the errors.
    /// 
    /// In order for this to work elmah must be setup in the web.config/app.config file
    /// </summary>
    /// <param name="ex"></param>
    public static void LogErrorManually(Exception ex)
    {
        if (HttpContext.Current != null)//website is logging the error
        {                
            var elmahCon = Elmah.ErrorSignal.FromCurrentContext();
            elmahCon.Raise(ex);
        }
        else//non website, probably an agent
        {                
            var elmahCon = Elmah.ErrorLog.GetDefault(null);
            elmahCon.Log(new Elmah.Error(ex));
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Как найти арифметическую прогрессию если неизвестно
  • Как найти дерево липу в лесу
  • Как правильно составить завещание на квартиру одному наследователю образец
  • Как найти делимое онлайн
  • Как найти сайты для комментариев