C# throw statement
In this chapter you will learn:
- What is C# throw statement
- Throwing an exception
- Example throw statement
- Rethrowing an exception
- Throw Exception in finally statement
Description
Exceptions can be thrown either by the runtime or in user code.
Syntax
The general form is:
throw exceptOb;
The exceptOb must be an object of an exception class derived from Exception.
Example
In this example, Display throws a System.ArgumentNullException:
using System;/*from w w w . jav a2s .c o m*/
class Test
{
static void Display (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
Console.WriteLine (name);
}
static void Main()
{
try { Display (null); }
catch (ArgumentNullException ex)
{
Console.WriteLine ("Caught the exception");
}
}
}
The code above generates the following result.
Rethrowing an exception
You can capture and rethrow an exception as follows:
try { ... }/*from w w w. j a v a2 s .c o m*/
catch (Exception ex)
{
// Log error
...
throw; // Rethrow same exception
}
Rethrowing in this manner lets you log an error without swallowing it.
Rethrow a more specific exception type. For example:
try/*ww w .ja v a 2s . c o m*/
{
... // Parse a DateTime from XML element data
}catch (FormatException ex){
throw new XmlException ("Invalid DateTime", ex);
}
Example 2
using System;// w w w. j a v a 2s .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:
- What is C# System Exception
- Common Exception Types
- Use the NullReferenceException
- Use ArgumentNullException
- Use OverflowException
- Use DivideByZeroException