// Exception Handling
using System;using Students;
public class ExceptionHandling {
static void Main(){
// We declare two students object references, but only instantiate one// Student object; s2 is given a value of null, indicating that it// isn't presently holding onto any object.
student s1 = new student();student s2 = null;
// Exception handling is now in place.
try { Console.WriteLine("Initializing students....");
// this line executes without throwing exception.
s1.Name = "Fred";
// This next line of code throws a NullReferenceException at run time because // s2 was never initialized to refer to an actual Student object ...
s2.Name = "Mary";
// ... and as soon as the exception is detected by the runtime, execution // jumps out of the try block -- none of the remaining code in // this try block will be executed -- and into the first catch block // below that is found to match a NullReferenceException, if any.
s1.Major = "MATH"; S2.Major = "SCIENCE";
Console.WriteLine("Initialization successfully completed.");} // end of try block
//Pseudocode.
catch (UnrelatedExceptionType e1) { // exception handing code fo this type of (hypothetical) exception // goes here ... but, since our example doesn't involve throwing this // particular type of exception at run time, this catch block will be // skipped over without being executed.
Console.WriteLine("UnrelatedExceptionType was detected ...");} // end of catch (UnrelatedExceptionType e1)
catch (NullReferenceException e2) {
// Here where we place the code for what the program should do if // a null reference ws detected at run time.
Console.WriteLine("Whoops -- we forgot to initialize all of the students!");} // end of catch (NullReference Exception e2)
finally {
// This code gets executed whether or not an exception occured; that is, // whether we made it through the try block without any exceptions being // thrown, or whether one of the catch blocks was triggered.
Console.WriteLine("Finally");} // end of finally
// After the finally block executes, control transfers to the// line of code immediately following block.
Console.WriteLine("Continuing along our merry way ...");}}
// This class has the simple name "Student".using System;
namespace Students
{public class student {
private string name; private string major;
public string Name {get{return name;}set {name = value;}}public string Major {get{return name;}set {major = value;}}
}}