Many classes encapsulate unmanaged resources.
These classes implement System.IDisposable
, which
defines a single parameterless method named Dispose to clean up these resources.
The using statement provides an elegant syntax for calling Dispose on an IDisposable
object within a finally block.
The following:
using (StreamReader reader = File.OpenText ("file.txt")) {
...
}
is equivalent to:
StreamReader reader = File.OpenText ("file.txt"); try { ... } finally { if (reader != null) ((IDisposable)reader).Dispose(); }
Exceptions can be thrown either by the runtime or in user code.
In this example, Display throws a System.ArgumentNullException
:
class Main { static void Display (string name) { if (name == null){ throw new ArgumentNullException ("name"); } Console.WriteLine (name); } static void Main() { try { Display (null); } catch (ArgumentNullException ex) { Console.WriteLine ("Caught the exception"); } } }
You can capture and rethrow an exception as follows:
try { ... } catch (Exception ex){ // Log error ... throw; // Rethrow same exception }
The most important properties of System.Exception are the following:
The following exception types are used widely throughout the CLR and .NET Framework.
System.ArgumentException
System.ArgumentNullException
System.ArgumentOutOfRangeException
System.InvalidOperationException
System.NotSupportedException
System.NotImplementedException
System.ObjectDisposedException
int
type defines two
versions of its Parse
method:
public int Parse (string input); public bool TryParse (string input, out int returnValue);
If parsing fails, Parse
throws an
exception; TryParse
returns false
.
You can implement this pattern by having the XXX
method call the TryXXX
method
as follows:
public return-type XXX (input-type input) { return-type returnValue; if (!TryXXX (input, out returnValue)) throw new YYYException (...) return returnValue; }