Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code not throw an exception?

Tags:

c#

exception

I expected the following lines of code to throw an exception since I am accessing the Value property of a nullable variable that is assigned a value of null. However, I do not get any exception when I execute the below:

int? x=null;
Console.WriteLine(x.Value==null);

But when I do:

Console.WriteLine(x.Value);

I do get an exception, as could be expected.

But what is the difference between the 2 ways of accessing x.Value? Why do I not get an exception in the first case? Both pieces of code are after all trying to access the x.Value property.

Note: I am running the above pieces of code on the www.compileonline.com website, btw. Not sure if trying on the Visual Studio compiler would yield different results, but I do not have access to Visual Studio currently.

TIA.

like image 286
user1510194 Avatar asked Jan 15 '14 07:01

user1510194


People also ask

How do you throw an exception?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

How do you throw an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

Which following operation may not throw exception?

*) Using swap() is an important technique for providing the strong exception guarantee, but only if swap() is non-throwing.

Can you throw an exception at any point?

Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.


1 Answers

When using the website compile online you point out, the mono compile does a rewrite/optimalization of your code:

using System.IO;
using System;

class Program
{
    static void Main()
    {
        int? x=null;
        Console.WriteLine(x.Value==null);  //-> Console.WriteLine(false);    
    }
}

Compiling the source code....

$mcs main.cs -out:demo.exe 2>&1

main.cs(9,38): warning CS0472: The result of comparing value type int' with null isfalse'

Compilation succeeded - 1 warning(s)

Executing the program....

$mono demo.exe

False

warning CS0472 tell you that, it is a bug in the online/mono compiler they are using.

like image 96
Peter Avatar answered Sep 18 '22 02:09

Peter