throw exception
In this chapter you will learn:
- Throwing an exception
- throw DivideByZeroException
- Rethrow an exception
- Throw Exception in finally statement
Manually throw an exception
The general form is:
throw exceptOb;
The exceptOb must be an object of an exception class derived from Exception.
using System;// j a v a 2 s.c o m
class MainClass {
public static int AnExceptionFunction(int value) {
if (value == 0) // Can't divide by zero
throw new DivideByZeroException("Divide By 0 error!");
int x = 20 / value;
return x;
}
public static void Main() {
int value = 0;
value = AnExceptionFunction(10); // This works ok
Console.WriteLine("Value = {0}", value);
AnExceptionFunction(0); // This doesn't
Console.WriteLine("Value = {0}", value);
}
}
throw DivideByZeroException
using System; //from j a v a2 s. c o m
class MainClass {
public static void Main() {
try {
Console.WriteLine("Before throw.");
throw new DivideByZeroException();
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Exception caught.");
}
Console.WriteLine("After try/catch block.");
}
}
The code above generates the following result.
Rethrow an exception
using System; //from j ava2s .c o m
class MainClass {
public static void Main() {
try {
genException();
}
catch(IndexOutOfRangeException) {
// recatch exception
Console.WriteLine("Fatal error -- " +
"program terminated.");
}
}
public static void genException() {
int[] numer = { 4, 8};
int d = 0;
for(int i=0; i<10; i++) {
try {
Console.WriteLine(numer[i] + " / " +
numer[i] + " is " +
numer[i]/d);
}
catch (DivideByZeroException) {
// catch the exception
Console.WriteLine("Can't divide by Zero!");
}
catch (IndexOutOfRangeException) {
// catch the exception
Console.WriteLine("No matching element found.");
throw; // rethrow the exception
}
}
}
}
The code above generates the following result.
Throw Exception in finally statement
using System;//from jav a 2 s. co m
using System.Collections;
public class MainClass
{
static void Main() {
try {
try {
ArrayList list = new ArrayList();
list.Add( 1 );
Console.WriteLine( "Item 10 = {0}", list[10] );
}
finally {
Console.WriteLine( "Cleaning up..." );
throw new Exception( "I like to throw" );
}
}
catch( ArgumentOutOfRangeException ) {
Console.WriteLine( "Oops! Argument out of range!" );
}
catch {
Console.WriteLine( "Done" );
}
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Commonly Used Exceptions Defined Within the System Namespace
- Use the NullReferenceException
- Use ArgumentNullException
- Use OverflowException
- Use DivideByZeroException