Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
Complete set: Intro to C - Bill Buchanan
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
In the above example (assuming that the file c:\sosuchfile.txt does no exist) we get<br />
the following output:<br />
Output of Exceptions 3.2.2<br />
Test started.<br />
An exception was raised.<br />
Finished.<br />
Test completed.<br />
The exception will be raised at the “new StreamReader” line – the following line<br />
does not get executed, instead execution jumps <strong>to</strong> the catch block, then the finally<br />
block then continues with the code outside the try/catch/finally structure.<br />
Without the try blocks the whole method will fail and the stack will unwind.<br />
There are different exceptions for different conditions.<br />
Examples of Exceptions 3.2.3<br />
System.NullReferenceException<br />
System.DivideByZeroException<br />
System.InvalidCastException<br />
System.IO.FileNotFoundException<br />
5.7 Finer control over exceptions<br />
<strong>Intro</strong>duction <strong>to</strong> .NET<br />
A host of different exceptions exist. We can test for a specific exception by including<br />
an exception reference in the catch clause. All exceptions inherit from System.Exception<br />
– this will catch any exception.<br />
We can perform further tests inside the catch block – we can examine ex.GetType()<br />
<strong>to</strong> find out exactly what exception was raised.<br />
Finer control<br />
try<br />
{<br />
DateTime x = (DateTime) new Object();<br />
}<br />
catch (System.InvalidCastException ex)<br />
{<br />
MessageBox.Show("The cast was invalid");<br />
}<br />
catch (Exception ex)<br />
{<br />
MessageBox.Show("Some kind of error happened :^(\n"+<br />
ex.ToString());<br />
}<br />
Agilent .NET Course: Module 5, page 6