0% found this document useful (0 votes)
66 views

Day Code Exceptions

The document discusses exception handling in C# programming. It provides 13 code listings as examples of try/catch blocks, different types of exceptions, throwing and rethrowing exceptions, and creating custom exception classes. The examples demonstrate basic and advanced exception handling techniques in C# like catching specific exception types, nested try/catch blocks, and using the finally block.

Uploaded by

brianweldt
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Day Code Exceptions

The document discusses exception handling in C# programming. It provides 13 code listings as examples of try/catch blocks, different types of exceptions, throwing and rethrowing exceptions, and creating custom exception classes. The examples demonstrate basic and advanced exception handling techniques in C# like catching specific exception types, nested try/catch blocks, and using the finally block.

Uploaded by

brianweldt
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

C# Programming Purvis Samsoodeen

listing 1
// Demonstrate exception handling.
using System;

class ExcDemo1 {
static void Main() {
int[] nums = new int[4];

try {
Console.WriteLine("Before exception is generated.");

// Generate an index out-of-bounds exception.


nums[7] = 10;
Console.WriteLine("this won't be displayed");
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("Index out-of-bounds!");
}
Console.WriteLine("After catch block.");
}
}

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];

Console.WriteLine("Before exception is generated.");

// Generate an index out-of-bounds exception.


nums[7] = 10;
Console.WriteLine("this won't be displayed");
}
}

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];

Console.WriteLine("Before exception is generated.");

// Generate an index out-of-bounds exception.


nums[7] = 10;
}
}

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.");

// Generate an index out-of-bounds exception.


nums[7] = 10;
Console.WriteLine("this won't be displayed");
}

/* Can't catch an array boundary error with a


DivideByZeroException. */
catch (DivideByZeroException) {
Console.WriteLine("Index out-of-bounds!");
}
Console.WriteLine("After catch block.");
}
}

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 };

for(int i=0; i < numer.Length; i++) {


try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +

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 };

for(int i=0; i < numer.Length; i++) {


try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
}
catch (IndexOutOfRangeException) {
Console.WriteLine("No matching element found.");
}
}
}
}

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 };

for(int i=0; i < numer.Length; i++) {


try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch {
Console.WriteLine("Some exception occurred.");
}
}
}

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 };

try { // outer try


for(int i=0; i < numer.Length; i++) {
try { // nested try
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) { // catch for inner try
Console.WriteLine("Can't divide by Zero!");
}
}
}
catch (IndexOutOfRangeException) { // catch for outer try
Console.WriteLine("No matching element found.");
Console.WriteLine("Fatal error -- program terminated.");
}
}
}

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

public static void GenException() {


// Here, numer is longer than denom.
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };

for(int i=0; i < numer.Length; i++) {


try {
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
}
catch (IndexOutOfRangeException) {
Console.WriteLine("No matching element found.");
throw; // rethrow the exception
}
}
}
}

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];

Console.WriteLine("Receiving " + what);


try {
switch(what) {
case 0:
t = 10 / what; // generate div-by-zero error
break;
case 1:
nums[4] = 4; // generate array index error.
break;
case 2:
return; // return from try block
}
}

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() {

for(int i=0; i < 3; i++) {


UseFinally.GenException(i);
Console.WriteLine();
}
}
}

listing 12
// Using Exception members.
using System;

class ExcTest {
public static void GenException() {
int[] nums = new int[4];

Console.WriteLine("Before exception is generated.");

// Generate an index out-of-bounds exception.


nums[7] = 10;
Console.WriteLine("this won't be displayed");
}
}

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) { }

// Override ToString for NonIntResultException.


public override string ToString() {
return Message;
}
}

class CustomExceptDemo {
static void Main() {

// Here, numer contains some odd values.


int[] numer = { 4, 8, 15, 32, 64, 127, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };

for(int i=0; i < numer.Length; i++) {


try {
if((numer[i] % denom[i]) != 0)
throw new
NonIntResultException("Outcome of " +
numer[i] + " / " + denom[i] + " is not even.");

Console.WriteLine(numer[i] + " / " +


denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
}

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) { }

public override string ToString() {


return Message;
}
}

// Create an exception derived from ExceptA


class ExceptB : ExceptA {
public ExceptB(string str) : base(str) { }

public override string ToString() {


return Message;
}
}

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;

// An exception for queue-full errors.


class QueueFullException : Exception {
public QueueFullException(string str) : base(str) { }
// Add other QueueFullException constructors here, if desired.

public override string ToString() {


return "\n" + Message;
}
}

// An exception for queue-empty errors.


class QueueEmptyException : Exception {
public QueueEmptyException(string str) : base(str) { }
// Add other QueueEmptyException constructors here, if desired.

public override string ToString() {


return "\n" + Message;
}
}

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

// Construct an empty queue given its size.


public SimpleQueue(int size) {
q = new char[size+1]; // allocate memory for queue
putloc = getloc = 0;
}

// Put a character into the queue.


public void Put(char ch) {
if(putloc==q.Length-1)
throw new QueueFullException("Queue Full! Max length is " +
(q.Length-1) + ".");

Page 9 of 12
C# Programming Purvis Samsoodeen

putloc++;
q[putloc] = ch;
}

// Get a character from the queue.


public char Get() {
if(getloc == putloc)
throw new QueueEmptyException("Queue is empty.");

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);

result = checked((byte)(a * b)); // this causes exception


Console.WriteLine("Checked result: " + result); // won't execute
}
catch (OverflowException exc) {
Console.WriteLine(exc);
}
}
}

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

result = (byte)(a * b); // this causes exception


Console.WriteLine("Checked result: " + result); // won't execute
}
}
catch (OverflowException exc) {
Console.WriteLine(exc);
}
}
}

Page 12 of 12

You might also like