22
loading...
This website collects cookies to deliver better user experience
string filePath = null;
File.Open(filePath, FileMode.Open);
System.ArgumentNullException HResult=0x80004003
Message=Path cannot be null. (Parameter 'path')
Source=System.Private.CoreLib
StackTrace: at
System.IO.Strategies.FileStreamHelpers.ValidateArguments(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize)
at System.IO.File.Open(String path, FileMode mode)
at Program.$(String[] args) in C:\Users\Caio Sousa\Program.cs:line 4
try
{
string filePath = null;
File.Open(filePath, FileMode.Open);
}
catch (ArgumentException)
{
Console.WriteLine("The informed parameter is invalid.");
}
finally
{
//Dispose resources
}
string filePath = null;
try
{
File.Open(filePath, FileMode.Open);
}
catch (ArgumentNullException)
{
Console.WriteLine("The informed parameter is null, please try again.");
}
catch (ArgumentException)
{
Console.WriteLine($"The parameter: {filePath} is invalid, please try again.");
}
When handling exceptions it is possible to catch multiple types of exceptions. This type of exception handling can increase the size of methods and sometimes it might not as clean as it could. Uncle bob suggests wrapping exceptions in other classes and handling errors with a common known exception object. Specially when working with third party libraries. In C# one can create custom exception classes that must inherit from the System.Exception base class.
Careful with null values, passing null values and returning null values, can be misleading and cause unwanted errors in application. One can use the throw keyword to raise an exception. When developing .NET application the ArgumentNullException can be used to throw exceptions regarding unwanted null values.
Avoid continuing program logic inside catch statement.