NET Centric Computing · Unit 2
Object-Oriented Programming and Events
Exam-focused notes for Object-Oriented Programming and Events (NET Centric Computing, BIT351): what the TU syllabus asks and how it has actually been tested, with 2 solved past questions from this unit.
Object-Oriented Programming and Events in short
This chapter covers how C# objects send notifications through delegates and events, and how a program deals with run time errors. Good error handling keeps an application from crashing and gives users clear messages.
What this unit covers
- Delegates and event handling
- Exception handling and error management
- Throwing and catching exceptions
- Input validation with exceptions
Throwing and catching exceptions
2081.1 · 10 marks
Differentiate between error and exception. Write a program to take the input for any five subjects and throw the exception if the given marks is negative or exceed 100.[10]
Show solved answerHide answer
Errors and exceptions, and validating five subject marks
How the two differ
In everyday use an error is any fault in a program, but as a technical term the two words describe faults of very different severity, and the .NET framework treats them differently from Java.
In .NET there is no separate Error base class. Everything that can be thrown derives from System.Exception. The distinction that matters is between the ordinary exceptions an application is expected to anticipate and recover from, such as FormatException, IOException or SqlException, and the fatal conditions raised by the runtime itself, such as OutOfMemoryException, StackOverflowException and AccessViolationException. The second group corresponds to what Java calls an Error, and .NET makes the point sharply: since .NET 2.0 a StackOverflowException cannot be caught at all, the process is simply terminated, because once the stack is gone there is no reliable way to keep running. The word error is also used for a compile time error, which the compiler refuses to build, and for an ordinary failure that a method reports through a return value or a status code rather than by throwing.
| Basis | Error (fatal condition) | Exception (handled condition) |
|---|---|---|
| Meaning | The environment can no longer run the program correctly | An abnormal but foreseeable situation in the application |
| Raised by | The CLR or the operating system | The application, a library, or the CLR for bad arguments |
| Typical examples | OutOfMemoryException, StackOverflowException, AccessViolationException | FormatException, DivideByZeroException, FileNotFoundException, a custom InvalidMarksException |
| Recoverable | Normally not; a stack overflow cannot even be caught | Yes, that is the point of catching it |
| Right response | Let the process fail and log it outside the process | try, catch, finally, or a using block |
| In Java | A separate java.lang.Error hierarchy | The java.lang.Exception hierarchy |
The practical consequence is that a program should catch the exception types it can actually do something about. Writing catch (Exception) around everything hides genuine defects such as a null reference, and it cannot rescue the fatal conditions anyway, so it buys nothing and costs a great deal in lost diagnostics.
Within the exception family, .NET also distinguishes exceptions by who is at fault. ArgumentException, ArgumentNullException and InvalidOperationException say the calling code used the API wrongly and should be fixed rather than caught, whereas IOException or a timeout describes the outside world misbehaving, which the caller must genuinely handle. A custom type for a business rule, like the marks rule below, belongs to that second group.
A C# program that validates five subject marks
The program reads marks for five subjects, and a method throws a custom exception when a value is negative or greater than 100. Each subject is validated inside its own try block so that one bad value does not stop the remaining subjects from being checked.
using System;
// A custom exception carries the offending data as well as the message.
public class InvalidMarksException : Exception
{
public string Subject { get; }
public int Marks { get; }
public InvalidMarksException(string subject, int marks, string message)
: base(message)
{
Subject = subject;
Marks = marks;
}
}
public static class Program
{
private static readonly string[] Subjects =
{ "Mathematics", "Physics", "Chemistry", "English", "Computer" };
private static void ValidateMarks(string subject, int marks)
{
if (marks < 0)
{
throw new InvalidMarksException(subject, marks,
subject + ": " + marks + " is negative, marks cannot fall below 0.");
}
if (marks > 100)
{
throw new InvalidMarksException(subject, marks,
subject + ": " + marks + " is too high, marks cannot exceed 100.");
}
}
public static void Main()
{
int[] marks = new int[Subjects.Length];
Console.WriteLine("Enter the marks obtained in five subjects.");
for (int i = 0; i < Subjects.Length; i++)
{
Console.Write(Subjects[i] + " (0 to 100): ");
string typed = Console.ReadLine();
// Console input is untrusted text, so it is parsed rather than assumed numeric.
// TryParse reports failure through its return value instead of throwing.
while (!int.TryParse(typed, out marks[i]))
{
Console.Write("Please type a whole number for " + Subjects[i] + ": ");
typed = Console.ReadLine();
}
}
int total = 0;
int accepted = 0;
Console.WriteLine();
Console.WriteLine("Checking the marks.");
for (int i = 0; i < Subjects.Length; i++)
{
try
{
ValidateMarks(Subjects[i], marks[i]);
Console.WriteLine(Subjects[i] + ": " + marks[i] + " is valid.");
total += marks[i];
accepted++;
}
catch (InvalidMarksException ex)
{
// Only the exception this code knows how to handle is caught.
Console.WriteLine("Invalid entry. " + ex.Message);
}
}
Console.WriteLine();
Console.WriteLine(accepted + " of 5 subjects accepted, total " + total + " marks.");
}
}
A sample run:
Enter the marks obtained in five subjects.
Mathematics (0 to 100): 85
Physics (0 to 100): -10
Chemistry (0 to 100): 110
English (0 to 100): 75
Computer (0 to 100): 90
Checking the marks.
Mathematics: 85 is valid.
Invalid entry. Physics: -10 is negative, marks cannot fall below 0.
Invalid entry. Chemistry: 110 is too high, marks cannot exceed 100.
English: 75 is valid.
Computer: 90 is valid.
3 of 5 subjects accepted, total 250 marks.
Two details are worth defending in the viva. int.TryParse is used instead of int.Parse because a typing mistake is expected input and not an exceptional condition, so it is cheaper and clearer to test the return value than to throw and catch a FormatException. The custom InvalidMarksException derives from Exception and adds the subject and the marks as properties, so the handler can report precisely which entry failed rather than parsing the message text. If the same validation were reached from an ASP.NET Core page instead of the console, the message would be surfaced through model validation and rendered with Razor, which HTML encodes the value so that whatever the user typed cannot be treated as markup.
Delegates and event handling
0 · 10 marks
Describe the roles of delegates in event handling. Illustrate the use of partial class with an example.[10]
Make Unit 2 stick
Practice BIT351 with flashcards & quizzes