C#, NullReferenceException is not catched - c#

Good afternoon. I cannot understand, why the block "catch" is not invoked, instead of it the programme stops working with NullReferenceException.
string? nullable_string_1 = null;
try
{
string non_nullable_string_1 = (string)nullable_string_1;
System.Console.WriteLine(non_nullable_string_1.Length);
}
catch (System.NullReferenceException nullReferenceException)
{
System.Console.WriteLine($"There is an invalid operation exception with message: \"{nullReferenceException.Message}\"");
}

using System;
public class Program
{
public static void Main()
{
string? nullableString = null;
try
{
string nonNullableString = (string)nullableString;
Console.WriteLine(nonNullableString.Length);
}
catch (NullReferenceException nullReferenceException)
{
Console.WriteLine($"There is an invalid operation exception with message: \"{nullReferenceException.Message}\"");
}
Console.WriteLine("After Exception Code Run");
}
}
Output - It's Working
[1]: https://i.stack.imgur.com/66Qum.png

Related

How to get StackTrace of called Assert?

I can get StackTrace for Exception. But I don't know how to get StackTrace for Assert. How to find out in which method Assert was called?
My code:
namespace ConsoleApp1
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
class MyProgram
{
static void Main(string[] agrs)
{
AppDomain.CurrentDomain.FirstChanceException += FirstChanceException!;
var foo = new Foo();
try
{
foo.FuncException();
}
catch { }
try
{
foo.FuncAssert();
}
catch { }
AppDomain.CurrentDomain.FirstChanceException -= FirstChanceException!;
}
static private void FirstChanceException(object source, FirstChanceExceptionEventArgs firstChanceExceptionEventArgs)
{
var ex = firstChanceExceptionEventArgs.Exception;
if (ex != null)
Console.WriteLine($" * * * \n Message: {ex.Message} \n StackTrace: {GetStackTrace(ex)} \n");
}
static private string GetStackTrace(Exception ex)
{
var list = new List<string>();
var trace = new StackTrace(ex, true);
foreach (var frame in trace.GetFrames())
{
list.Add($"{frame.GetMethod()?.ReflectedType?.Name}.{frame.GetMethod()?.Name}");
}
return string.Join(" -> ", list);
}
public class Foo
{
public void FuncException()
{
throw new Exception("Exception - FuncException");
}
public void FuncAssert()
{
Assert.Fail("Assert - FuncAssert");
}
}
}
}
You register an event handler for AppDomain.CurrentDomain.FirstChanceException:
AppDomain.CurrentDomain.FirstChanceException += FirstChanceException;
You call Assert.Fail():
public class Foo
{
public void FuncAssert()
{
Assert.Fail("Assert - FuncAssert");
}
}
I assume that you expect to see the whole call stack in the exception. But call stack is only gathered when exception is bubbling through the stack.
And AppDomain.FirstChanceException catches the exception right in the place where it's thrown.
Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.
https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.firstchanceexception
So, I would say that you are trying to do something wrong.
What is the problem that you are actually trying to solve?
This code will work well because I let exception to bubble along the call stack and be caught:
try
{
foo.FuncAssert();
}
catch (Exception ex)
{
Console.WriteLine($" * * * \n Message: {ex.Message} \n StackTrace: {GetStackTrace(ex)} \n");
}
Output:
Message: Assert - FuncAssert
StackTrace: Assert.ReportFailure -> Assert.Fail -> Assert.Fail -> Foo.FuncAssert -> MyProgram.Main

Exit the function/method if an exception occurs

I'm trying to find a code to exit the whole method if an exception occurs in a sub method. I tried adding return in catch section of Subfunction() but the process will continue to Thirdfunction()
public static void Mainfunction()
{
try
{
//some code
//some code
Subfunction();
ThirdFunction();
}
catch(Exception ex)
{
//write to log
}
}
public static void Subfunction()
{
try
{
//some code
//some code
}
catch (Exception ex)
{
//write to log
}
}
So basically if an error occured in the Subfuntion() I want to stop the process from the Mainfunction() without continuing to the ThirdFunction(). Any help will be highly appreciated. Thanks
if an error occured in the Subfuntion() I want to stop the process
from the Mainfunction()
The simplest way to remove try/catch in your method Subfunction
If you want to keep the try/catch in this method, (for logging or something), rethrown exception
public static void Main()
{
try
{
Subfunction();
Thirdfunction();
}
catch(Exception ex)
{
}
}
public static void Subfunction()
{
try
{
throw new AccessViolationException();
}
catch (Exception ex)
{
throw;
}
}
There are basically two sets of possible solutions: With use of Exceptions and without.
With the use of exceptions, I'd recommend to just let it bubble up , as I've already said in comments.
Then you can rethrow:
try {
// exception here
}
catch(Exception ex)
{
throw;
// Attention: this is _different_ from "throw ex" !!
}
Pay attention here:
You can also use the throw e syntax in a catch block to instantiate a new exception that you pass on to the caller. In this case, the stack trace of the original exception, which is available from the StackTrace property, is not preserved.
See throw (C# Reference) (emphasis by me)
Coming over from Java myself, this is something people like myself will trip over during transitioning from Java to .Net. So if you got "java guys" new on the team: don't be harsh on them, just point them to the docs.
You can wrap:
try {
// exception here
}
catch(Exception inner)
{
throw new MyCustomException( "Some custom message", inner);
}
BTW: It is generally not a good idea to catch Exception. Most of the time you'd want to catch specific exceptions that you can actually handle.
The other class of solutions is without bubbling up exceptions:
Return value:
public static bool Subfunction()
{
bool success = true;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = false;
}
return success;
}
Or with return or error codes:
// DO NOT USE MAGIC NUMBERS !
private static readonly int SUCCESS_INDICATOR = 0;
private static readonly int ERROR_INDICATOR = 1;
// TODO DOCUMENT which errorcodes can be expected and what they mean!
public static int Subfunction()
{
int success = SUCCESS_INDICATOR;
try
{
//some code
//some code
}
catch (Exception ex)
{
// TODO write error log!
success = ERROR_INDICATOR;
}
return success;
}
Especially with "C-Guys" on the team you may stumble across this one. (No offense - just my experience)
Or with a state object ...
public static void Mainfunction()
{
try
{
//some code
//some code
ISuccessIndicator success = new ISIImplementation();
Subfunction( success );
if( !succes.HasException )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThrirdFunction or "else" branch are caught here.
}
}
public static void Subfunction( ISuccessIndicator result )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
result.HasException=true;
result.Exception = ex;
}
}
public interface ISuccessIndicator
{
Exception Exception {get; set;}
bool HasException {get; set;}
}
And if you are really crazy you could ...
public static void Mainfunction()
{
try
{
//some code
//some code
Exception ex = null;
Subfunction( ref ex );
if( ex == null ) // or more modern: ( ex is null )
{
ThirdFunction();
}
else
{
// handle exception from Subfunction
}
}
catch(Exception ex)
{
//write to log
//Exceptions from ThirdFunction or "else" branch caught here.
}
}
public static void Subfunction( ref Exception outEx )
{
try
{
//some code
//some code
}
catch (Exception ex)
{
outEx = ex;
}
}
Please mind, that I in no way would encourage using the latter. But it is possible ... and OP asked for possibilities.
Disclaimer: All snippets untested. Who finds errors can keep them (but please write a comment, so I can fix them).

C# Try Catch Statement Query

I have a question about Try Catch statements in C#.
For example if I had a statement as such
try
{
string text = sometext;
var Auto_IMPORT = new AutoImport();
Auto_IMPORT.StartProcessing();
Console.WriteLine(sometext);
}
catch(Exception Ex)
{
//Would this catch AutoImport.StartProcessing() exceptions?
Console.WriteLine(ex.Message);
}
AutoImport is a Class Library and i'm calling some logic to start processing.
If an exception occurred within the logic inside AutoImport.StartProcessing() would this try statement catch that exception or would it be out of scope by then?
Thanks In Advance
It depends on the behavior of Auto_IMPORT.StartProcessing(). If no exception is caught in it, then yes, you will get an exception. On the other hand, if the internal code off Auto_IMPORT catches the exception, and doesn't throw a new exception, then you wont get any exceptions.
Yes.
It catches any errors that are in the try block. Doesn't matter if they're in some method of some class.
Tested with:
class _Class
{
public string name;
public void myMethod()
{
int i;
string s = "asda";
i = int.Parse(s);
}
}
class Program
{
static void Main(string[] args)
{
try
{
_Class blah = new _Class();
blah.name = "Steve";
blah.myMethod();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
Caught exception at int.Parse

C# Syntax error

Is it Syntax error or compiliing error?
using System;
namespace AAA
{
class MyException : Exception{
}
class My2Exception : MyException{
}
class MainClass
{
public static void Main (string[] args)
{
try{
throw new MyException();
}
catch(Exception e){ // compiler says that this catch all exception occur error? Is it syntax error?
}
catch(MyException m){ // Syntax error
}
}
}
}
Is it kind of syntax error?
Is this error syntax error?
thanks
Since a catch block for type Exception is the least specific exception handler possible, the need to provide a more specific catch block is not only redundant, but in C# it's a compile time error. Thus, in a multi-catch block, you should always specify the most generic catch block last:
using System;
namespace AAA
{
class MyException : Exception
{
}
class MainClass
{
public static void Main (string[] args)
{
try
{
throw new MyException();
}
catch (MyException m)
{
//TODO: something
}
catch (Exception e)
{
//TODO: something
}
}
}
}
Exception is a more general class than MyException that's why you should catch it last.
As mentioned by Shaharyar it a 'semantic error'
try{
throw new MyException();
}
catch(MyException m){
}
catch(Exception e){ // Syntax error
}

How to remove try...catch block from many different functions [duplicate]

This question already has answers here:
Is there a way to catch all unhandled exceptions thrown by a given class?
(6 answers)
Closed 8 years ago.
I have a lot of classes (WCF services) that contain several function. Now I need to handle errors, but I don't want to create a block try ... catch within each function (for error handling).
How can I make try...catch in any class (or something else) so that we catch errors but did not write the same block within each method?
There will always be some duplication of code but you can reduce it to one line
public static class ExceptionHandler
{
public static void Run(Action action)
{
try
{
a();
}
catch(Exception e)
{
//Do Something with your exception here, like logging
}
}
}
and then just call
ExceptionHandler.Run(yourAction);
you can add overloads for functions and what not but this approach is not ideal. As you may want to catch specific exceptions in certain cases.
Since you did not provide code specifically, I will write some sample code to make it more obvious. If you have this:
public class MyClass
{
public void Method1ThatCanThrowException()
{
try
{
// the Method1 code that can throw exception
}
catch (MySpecificException ex)
{
// some specific error handling
}
}
public object Method2ThatCanThrowException()
{
try
{
// the Method2 code that can throw exception
}
catch (MySpecificException ex)
{
// the same specific error handling
}
}
}
So, if you intend to have single place error handling, you can use lambda, and the help of a private method:
private T CheckAndCall<T>(Func<T> funcToCheck)
{
try
{
return funcToCheck();
}
catch (MySpecificException ex)
{
// the old specific error handling
}
}
Notice the use of the Func<T> delegate. This is because you may need to wrap the try-catch logic around some code that can return a value.
Then you can rewrite the above methods like this:
public void Method1ThatCanThrowException()
{
CheckAndCall(
() =>
{
// the Method1 code that can throw exception
return null;
});
}
public object Method2ThatCanThrowException()
{
return CheckAndCall(
() =>
{
// the Method2 code that can throw exception
return someObject;
});
}
For example, rather than having to do this:
public class Program
{
public static string ReadFile(string filename)
{
//A BCL method that throws various exceptions
return System.IO.File.ReadAllText(filename);
}
public static void Main(string[] args)
{
try
{
Console.Write(ReadFile("name.txt"));
}
catch (Exception e)
{
Console.WriteLine("An error occured when retrieving the name! {0}", e.Message);
}
try
{
Console.Write(ReadFile("age.txt"));
}
catch (Exception e)
{
Console.WriteLine("An error occured when retrieving the age! {0}", e.Message);
}
}
}
You could implement a "Try..." method, using the ref or out keyword as appropriate:
public class Program
{
public static bool TryReadFile(string filename, out string val)
{
try
{
val = System.IO.File.ReadAllText(filename);
return true;
}
catch (Exception)
{
return false;
}
}
public static void Main(string[] args)
{
string name, age;
Console.WriteLine(TryReadFile("name.txt", out name) ? name : "An error occured when retrieving the name!");
Console.WriteLine(TryReadFile("age.txt", out age) ? age: "An error occured when retrieving the age!");
}
}
The downside to this approach is that you can't act upon a specific exception, but in the case of simply determining if an operation has or has not succeeded, I find this to be a syntactically clean approach.

Categories