Day Code Exceptions
Day Code Exceptions
listing 1
// Demonstrate exception handling.
using System;
class ExcDemo1 {
static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine("Before exception is generated.");
listing 2
// An exception can be generated by one method and caught by another.
using System;
class ExcTest {
// Generate an exception.
public static void GenException() {
int[] nums = new int[4];
class ExcDemo2 {
static void Main() {
try {
ExcTest.GenException();
}
catch (IndexOutOfRangeException) {
// Catch the exception.
Console.WriteLine("Index out-of-bounds!");
}
Console.WriteLine("After catch block.");
}
}
Page 1 of 12
C# Programming Purvis Samsoodeen
listing 3
// Let the runtime system handle the error.
using System;
class NotHandled {
static void Main() {
int[] nums = new int[4];
listing 4
// This won't work!
using System;
class ExcTypeMismatch {
static void Main() {
int[] nums = new int[4];
try {
Console.WriteLine("Before exception is generated.");
listing 5
// Handle error gracefully and continue.
using System;
class ExcDemo3 {
static void Main() {
int[] numer = { 4, 8, 16, 32, 64, 128 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
Page 2 of 12
C# Programming Purvis Samsoodeen
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
}
}
}
}
listing 6
// Use multiple catch clauses.
using System;
class ExcDemo4 {
static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
listing 7
// Use the "catch all" catch.
using System;
class ExcDemo5 {
static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
Page 3 of 12
C# Programming Purvis Samsoodeen
listing 8
// Use a nested try block.
using System;
class NestTrys {
static void Main() {
// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
listing 9
// Manually throw an exception.
using System;
class ThrowDemo {
static void Main() {
try {
Console.WriteLine("Before throw.");
throw new DivideByZeroException();
}
catch (DivideByZeroException) {
Console.WriteLine("Exception caught.");
}
Console.WriteLine("After try/catch statement.");
}
}
listing 10
// Rethrow an exception.
using System;
class Rethrow {
Page 4 of 12
C# Programming Purvis Samsoodeen
class RethrowDemo {
static void Main() {
try {
Rethrow.GenException();
}
catch(IndexOutOfRangeException) {
// recatch exception
Console.WriteLine("Fatal error -- program terminated.");
}
}
}
listing 11
// Use finally.
using System;
class UseFinally {
public static void GenException(int what) {
int t;
int[] nums = new int[2];
Page 5 of 12
C# Programming Purvis Samsoodeen
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
return; // return from catch
}
catch (IndexOutOfRangeException) {
Console.WriteLine("No matching element found.");
}
finally {
Console.WriteLine("Leaving try.");
}
}
}
class FinallyDemo {
static void Main() {
listing 12
// Using Exception members.
using System;
class ExcTest {
public static void GenException() {
int[] nums = new int[4];
class UseExcept {
static void Main() {
try {
ExcTest.GenException();
}
catch (IndexOutOfRangeException exc) {
Console.WriteLine("Standard message is: ");
Console.WriteLine(exc); // calls ToString()
Console.WriteLine("Stack trace: " + exc.StackTrace);
Console.WriteLine("Message: " + exc.Message);
Console.WriteLine("TargetSite: " + exc.TargetSite);
}
Console.WriteLine("After catch block.");
}
}
Page 6 of 12
C# Programming Purvis Samsoodeen
listing 13
// Use a custom exception.
using System;
// Create an exception.
class NonIntResultException : Exception {
/* Implement all of the Exception constructors. Notice that
the constructors simply execute the base class constructor.
Because NonIntResultException adds nothing to Exception,
there is no need for any further actions. */
public NonIntResultException() : base() { }
public NonIntResultException(string str) : base(str) { }
public NonIntResultException(string str, Exception inner) :
base(str, inner) { }
protected NonIntResultException(
System.Runtime.Serialization.SerializationInfo si,
System.Runtime.Serialization.StreamingContext sc) :
base(si, sc) { }
class CustomExceptDemo {
static void Main() {
Page 7 of 12
C# Programming Purvis Samsoodeen
catch (IndexOutOfRangeException) {
Console.WriteLine("No matching element found.");
}
catch (NonIntResultException exc) {
Console.WriteLine(exc);
}
}
}
}
listing 14
// Derived exceptions must appear before base class exceptions.
using System;
// Create an exception.
class ExceptA : Exception {
public ExceptA(string str) : base(str) { }
class OrderMatters {
static void Main() {
for(int x = 0; x < 3; x++) {
try {
if(x==0) throw new ExceptA("Caught an ExceptA exception");
else if(x==1) throw new ExceptB("Caught an ExceptB exception");
else throw new Exception();
}
catch (ExceptB exc) {
Console.WriteLine(exc);
}
catch (ExceptA exc) {
Console.WriteLine(exc);
}
catch (Exception exc) {
Console.WriteLine(exc);
}
}
}
}
Page 8 of 12
C# Programming Purvis Samsoodeen
listing 15
// Add exception handling to the queue classes.
using System;
listing 16
// A simple, fixed-size queue class for characters that uses exceptions.
class SimpleQueue : ICharQ {
char[] q; // this array holds the queue
int putloc, getloc; // the put and get indices
Page 9 of 12
C# Programming Purvis Samsoodeen
putloc++;
q[putloc] = ch;
}
getloc++;
return q[getloc];
}
}
listing 17
// Demonstrate the queue exceptions.
class QExcDemo {
static void Main() {
SimpleQueue q = new SimpleQueue(10);
char ch;
int i;
try {
// Overrun the queue.
for(i=0; i < 11; i++) {
Console.Write("Attempting to store : " +
(char) ('A' + i));
q.Put((char) ('A' + i));
Console.WriteLine(" -- OK");
}
Console.WriteLine();
}
catch (QueueFullException exc) {
Console.WriteLine(exc);
}
Console.WriteLine();
try {
// Over-empty the queue.
for(i=0; i < 11; i++) {
Console.Write("Getting next char: ");
ch = q.Get();
Console.WriteLine(ch);
}
}
catch (QueueEmptyException exc) {
Console.WriteLine(exc);
}
}
}
listing 18
// Using checked and unchecked.
using System;
Page 10 of 12
C# Programming Purvis Samsoodeen
class CheckedDemo {
static void Main() {
byte a, b;
byte result;
a = 127;
b = 127;
try {
result = unchecked((byte)(a * b));
Console.WriteLine("Unchecked result: " + result);
listing 19
// Using checked and unchecked with statement blocks.
using System;
class CheckedBlocks {
static void Main() {
byte a, b;
byte result;
a = 127;
b = 127;
try {
unchecked {
a = 127;
b = 127;
result = (byte)(a * b);
Console.WriteLine("Unchecked result: " + result);
a = 125;
b = 5;
result = (byte)(a * b);
Console.WriteLine("Unchecked result: " + result);
}
checked {
a = 2;
b = 7;
result = (byte)(a * b); // this is OK
Console.WriteLine("Checked result: " + result);
a = 127;
b = 127;
Page 11 of 12
C# Programming Purvis Samsoodeen
Page 12 of 12