Summary

This document provides an overview of exception handling in C# programming. It covers the exception hierarchy, try-catch blocks, and manually throwing exceptions. This handbook is suitable for those studying C# programming.

Full Transcript

IT1811 Exception Handling The Exception Hierarchy Exception is represented by classes. All the exceptions are subclasses in the built-in exception class named Exception, wherein it is a part of namespace System. Two (2) Types of Exceptions...

IT1811 Exception Handling The Exception Hierarchy Exception is represented by classes. All the exceptions are subclasses in the built-in exception class named Exception, wherein it is a part of namespace System. Two (2) Types of Exceptions o ApplicationException – These exceptions are user program-generated. o SystemException – These exceptions are generated by Common Language Runtime (CLR). Here are the few exceptions which are commonly used: System.Exception – This is at the top of the standards’ exceptions hierarchy. The runtime system in C# generates all the exceptions. System.ArithmeticException – Errors in arithmetic or conversion operation will be thrown in this exception. System.OverflowException – When an overflow occurs in a checked operation, it will be thrown in OverflowException. System.ArgumentException – Any invalid argument in a method will be thrown in this exception. System.ArgumentNullException – If there is an unacceptable argument passed to a method, it will be thrown in ArgumentNullException. System.IndexOutOfRangeException – Throw in this exception when attempting to index an array through an index that is either less than zero or greater than the maximum length of index. System.OutOfMemoryException – If the available memory becomes too low to accommodate a memory allocation request, it will be thrown in OutOfMemoryException. System.StackOverflowException – The exception StackOverflowException is called when the execution stack is exhausted by having too many pending method calls. System.FormatException – This exception checks the format of the string or argument if it is invalid. The try-catch Block Handling exceptions in C# uses four (4) keywords: try – This keyword is used to check for the occurrence of any exceptions enclosed to it. catch – This keyword catches the exception that is thrown on the occurrence of exception in a try block. throw – It is used to throw an exception manually. finally – This keyword executes a given statement even if the exception is thrown or not thrown. This block cannot transfer control by using break, continue, return, or goto. try{ // code to be check for exceptions }catch(Type_of_Exception var_name){ // exception are handled here. }catch(Type_of_Exception var_name){ // exception are handled here }finally{ // clean up any codes that are allocated in try block } Throwing an Exception To catch exceptions, use the try-catch block to check the errors in the code and generate in the runtime system automatically. Manually throwing using the throw keyword can also be used. The syntax is throw new exception_Object; The exception_Object is an instance of a class derived from the Exception class. The new operator is used to create a new object. 03 Handout 1 *Property of STI [email protected] Page 1 of 3 IT1811 private int num1, num2; private void btnCompute_Click(object sender, EventArgs e){ num1 = Convert.ToInt32(txtNum1.Text); num2 = Convert.ToInt32(txtNum2.Text); if(num1 == 0 || num2 == 0) throw new DivideByZeroException("Invalid Input"); else MessageBox.Show("Total: " + GetQuotient(num1, num2)); } public int GetQuotient(int x, int y){ return x/y; } Listing 1. Using throw without the try-catch block Listing 1 shows how DivideByZeroException is thrown manually. The exception was caught in an if condition that validates the input using the new operator. If the condition is equal to 0, the thrown exception will be called. The throw keyword can be used outside of the try-catch block, but without the try-catch block, there will be an interruption in the process. This will show an error message to the console and the application will be closed. If throwing an exception, a catch block is needed. private void btnCompute_Click(object sender, EventArgs e) { try{ num1 = Convert.ToInt32(txtNum1.Text); num2 = Convert.ToInt32(txtNum2.Text); if(num1 == 0 || num2 ==0) throw new DivideByZeroException(); else MessageBox.Show("Total: " + GetQuotient(num1, num2)); } catch(DivideByZeroException dze) { Console.WriteLine("Divide By Zero Message: " + dze.Message); } catch(FormatException fe) { Console.WriteLine("Format Exception Message: " + fe.Message); } } public int GetQuotient(int x, int y){ return x/y; } Listing 2. Using throw with try-catch block Listing 2 contains two (2) catch blocks to check the format and check if the entered number is zero. In contrast, Listing 1 only shows an exception that will be thrown and will not catch when the exception occurs, while Listing 2 demonstrates how a catch block catches a manually thrown exception. The DividebyZeroException is thrown by using throw keyword and caught in a catch block and display the message. Creating Own Exception Creating one’s own exception is possible in.NET Framework because it provides a facility to create custom exceptions.Ina customized exception, it requires or inherits those exceptions in System.Exception class or one of its standard derived classes. The simplest form for a custom exception class is public class CustomizeException: Exception{ //code here } 03 Handout 1 *Property of STI [email protected] Page 2 of 3 IT1811 Once the custom exception class is created and is derived from the Exception class, add a constructor using the following format: public class CustomizeException: Exception{ public CustomException(string str): base(str){ } } After that, the custom exception acts like other standard exceptions. One can pass a string that describes the cause oferror. Listing 3 demonstrates the creation of the custom exception class InvalidUserInputException that throws manually and catches the exception using the catch block. ///InvalidUserInputException Class public class InvalidUserInputException : Exception{ public InvalidUserInputException(string age): base(age){ } } ///CustomExcep Class with Form public partial class CustomExcep : Form { public CustomExcep() { InitializeComponent(); } private void btnCheck_Click(object sender, EventArgs e) { try{ checkAge(Int32.Parse(txtStudAge.Text)); } catch(InvalidUserInputException ex) { Console.WriteLine("Message: " + ex.Message); } } public void checkAge(int age){ if(age == 0 || age < 18) { throw new InvalidUserInputException("Not in legal age!"); } else { MessageBox.Show("Legal Age!"); } } } Listing 3. Custom Exception REFERENCES: Deitel, P. & Deitel, H. (2015). Visual C# 2012 how to program (5 th ed.). USA: Pearson Education, Inc. Gaddis, T. (2016). Starting out with visual C# (4 th ed.). USA: Pearson Education, Inc. Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR. Miles, R. (2016). Begin to code with C#. Redmond Washington: Microsoft Press. Doyle, B. (2015). C# programming: from problem analysis to program design (5 th ed.). Boston, MA: Cengage Learning. 03 Handout 1 *Property of STI [email protected] Page 3 of 3 IT1811 Threads Life Cycle of a Thread Thread This is a class in C#.net that can be found in the System.Threading namespace. It is used to create and control threads in a system or application, in which the properties and methods are already provided. This is an independent execution unit containing a piece of code. When a process begins, the main thread is started. All threads within a process share the same state and memory space and communicate with each other to perform different tasks. Main Thread When using the Thread class, the first thread to be performed in a process is known as the main thread. The other threads that are made using the Thread class are known as the child thread of the main thread. //Sample Main Thread Thread basicThread = Thread.CurrentThread; basicThread.Name = "Basic C# Thread"; Console.WriteLine("Current Thread: {0}", basicThread.Name); Child Thread Creating a child thread for the main thread should write or create a delegate object, passing a callback method to it as a parameter. When the thread object is created, the delegate will be used to initialize the thread object. To define a callback method in the delegate, use ThreadStart to execute the code when the thread started. A ThreadStart delegate represents a method that runs in the Thread class. See sample code below. //Sample Child Thread private void btnRunThread_Click(object sender, EventArgs e) { ThreadStart delThread = new ThreadStart(ChildThreadMethod); Thread childThread = new Thread(delThread); Thread.CurrentThread.Name = "Main Thread"; Console.WriteLine(Thread.CurrentThread.Name); childThread.Start(); } //method public void ChildThreadMethod() { Console.WriteLine("Calling child thread"); } When using the Thread class, there are different ways to control it. The speed of execution can be paused, resumed, destroyed, or controlled. Thread has a state that determines when and where it undergoes during its life cycle. Life Cycle of a Thread (Harwani, 2015) 1. A new thread begins its life cycle in the Unstarted state. 2. The thread remains in the Unstarted state until the Thread method Start is called, which places the thread in the Started (also known as Ready or Runnable) state. 3. The highest priority Started thread enters the Running state. 4. A Running thread enters the Stopped state when its job or task is over. Also, a Running thread can be forced to the Stopped state by calling the Abort method. The Abort method throws a ThreadAbortException in the thread, normally causing the thread to terminate. 5. A thread enters the Blocked state when the thread issues an input/output (I/O) request. In other words, the operating system blocks the thread to perform the I/O operations. The CPU time is not assigned to a Blocked thread. 6. After I/O operations are complete, the Blocked thread returns to the Started state so it can resume execution. 7. A Running thread may enter the WaitSleepJoin state either when it is asked to sleep for the specified number of 04 Handout 1 *Property of STI [email protected] Page 1 of 4 IT1811 milliseconds or when the Monitor method Wait is called. From the WaitSleepJoin state, a thread returns to the Started state when another thread invokes the Monitor method Pulse or PulseAll. The Pulse method moves the next waiting thread back to the Started state. The PulseAll method moves all waiting threads back to the Started state. 8. A sleeping thread returns to the Started state when the specified sleep duration expires. 9. Any thread in the WaitSleepJoin state can return to the Started state if the sleeping or waiting thread’s Interrupt method is called by another thread in the program. 10. If a thread cannot continue executing unless another thread terminates, it calls the other thread’s Join method to join the two (2) threads. When two (2) threads are joined, the waiting thread leaves the WaitSleepJoin state when the other completes execution. Figure 1. Block Diagram of Thread's Life Cycle Source: Learning object-oriented programming in C# 5.0, 2015. p. 439 List of Thread States (Harwani, 2015) Unstarted – A thread is created within the Common Language Runtime (CLR) but has not started. Ready – A thread is ready to run and is waiting for the CPU time. Running – A thread is in running mode after invoking its Start method. WaitSleepJoin – A running thread is suspended temporarily by invoking either the Sleep method or the monitor’s Wait method. Started – A suspended thread resumes to Started state when the conditions for which is it was suspended are no longer valid. Blocked – A thread is blocked when it is waiting for a resource or I/O operations. Stopped – A thread has finished its task. private Thread _childThread; private void btnCheck_Click(object sender, EventArgs e) { ThreadStart delThreadObj = new ThreadStart(ThreadCycle); Console.WriteLine("Will Create Child Thread In Main Thread…"); _childThread = new Thread(delThreadObj); _childThread.Start(); Thread.Sleep(3000);//3 seconds before aborting the thread. Console.WriteLine("Aborting Child Thread"); _childThread.Abort(); } public void ThreadCycle() { try 04 Handout 1 *Property of STI [email protected] Page 2 of 4 IT1811 { Console.WriteLine("Thread starts here!"); Console.WriteLine("Paused for 2 seconds: child thread"); Console.Write("Countdown: "); for(int x = 2; x > 0; x--){ Console.Write(x + " "); Thread.Sleep(1000); } Console.WriteLine("\nChild thread resume"); Console.WriteLine("WaitSleepJoin State: (Child Thread):" + (_childThread.ThreadState == ThreadState.WaitSleepJoin)); Thread.Sleep(1000); //Thread sleep or pause for 1 second Console.WriteLine("Child Thread Done."); } catch(ThreadAbortException ex) { Console.WriteLine("Exception Message: " + ex.Message); } finally{ Console.WriteLine("Finally Block the Thread!"); } } The code above explains how to process different states of a child thread or the life cycle itself. If the thread is aborted, an exception will be thrown named ThreadAbortException. This exception can be caught but is automatically rethrown at the end of the catch block. The Thread class also provides some properties and methods to access information about the thread. Properties CurrentThread – It returns the current thread that is running. IsAlive – It returns a Boolean value indicating the execution status of the recent thread. IsBackground – It is used to get or set a value that indicates whether the thread is a background thread or not. Name – It is used to get or set the name of the thread. Priority – It is used to get or set a value that represents the priority of a thread. ThreadState – It is used to get the value that contains the states of the recent thread. Methods public void Abort() – It terminates the thread when calling this method and raises ThreadAbortException in the thread. public void Interrupt() – It interrupts the thread that is in the state of WaitSleepJoin. public void Join() – It is used to stop the calling thread until a thread terminates. public static void ResetAbort() – It is used to withdraw an abort request for the ongoing thread. public void Start() – It is used to start a thread. public static void Sleep() – It is used to pause a thread for the stated number in milliseconds. Multithreading In operating systems, multithreading is a common feature that allows your application to have more than one (1) execution path at the same time. In multithreading, the CPU is assigned to each thread for a time slice before moving on to the next thread. In other words, the CPU serves each thread or a given time interval in a round-robin fashion (Harwani, 2015, p. 438). private int x = 2; private int y = 2; 04 Handout 1 *Property of STI [email protected] Page 3 of 4 IT1811 private Thread _childThread1, _childThread2, _childThread3; private void btnStart_Click(object sender, EventArgs e) { Console.WriteLine("--------"); Console.WriteLine("Main Thread Running…"); ThreadStart delObjThread = new ThreadStart(Method1); _childThread1 = new Thread(delObjThread); _childThread1.Name = "Child Thread 1"; _childThread2 = new Thread(delObjThread); _childThread2.Name = "Child Thread 2"; _childThread3 = new Thread(new ThreadStart(Method2)); _childThread3.Name = "Child Thread 3"; _childThread1.Start(); _childThread2.Start(); _childThread3.Start(); _childThread1.Join(); _childThread2.Join(); _childThread3.Join(); Console.WriteLine("Value of x: " + x); Console.WriteLine("Value of y: " + y); } ///Methods to be called in ThreadStart delegate public void Method1(){ Console.WriteLine(Thread.CurrentThread.Name + " running..."); x++; } public void Method2(){ Console.WriteLine(Thread.CurrentThread.Name + " running..."); y++; } The sample program above shows how multithreading is implemented. It contains two (2) int variables and three (3) child threads. This program uses the Join() method to make the main thread wait until the three (3) child threads finish their task. The two (2) child threads (_childThread1 and _childThread2) are gotten from the same resource simultaneously for manipulation, which is known as race condition. REFERENCES: Deitel, P. & Deitel, H. (2015). Visual C# 2012 how to program (5th ed.). USA: Pearson Education, Inc. Gaddis, T. (2016). Starting out with Visual C# (4th ed.). USA: Pearson Education, Inc. Harwani, B. (2015). Learning object-oriented programming in C# 5.0. USA: Cengage Learning PTR. Miles, R. (2016). Begin to code with C#. Redmond Washington: Microsoft Press. Doyle, B. (2015). C# programming: from problem analysis to program design (5th ed.). Boston, MA: Cengage Learning. 04 Handout 1 *Property of STI [email protected] Page 4 of 4

Use Quizgecko on...
Browser
Browser