Advertisement
try
{
//An object of IOException exception class is created using "new" keyword
//And, thrown by using the throw keyword
//Which will raise an exception
throw new IOException();
}
catch(IOException io)
{
// An existing exception class object referenced by "io" of type "IOException", is thrown.
throw io;
}
//C# Using throw keyword to throw an exception out of try block
using System;
using System.IO;
class ThrowEx
{
public static void Main(String[] ar)
{
try
{
// "throw" is explicitly throwing an exception object of type "IOException"
throw new IOException();
}
catch(IOException ioExp)
{
Console.WriteLine("Thrown Exception - " +ioExp);
}
}
}
Thrown Exception - System.IO.IOException: I/O error occurred.
at ThrowEx.Main(String[] ar)
Advertisement
//C# Using throw keyword, to throw an exception already caught in the catch block
using System;
class A
{
public static void Main(String[] ar)
{
try
{
//Defining an array
int[] arr = {1,2,3,4};
//Trying to access an invalid index 5, an IndexOutOfRangeException will be thrown
Console.WriteLine("Value ="+arr[5]);
}
catch(IndexOutOfRangeException e)
{
Console.WriteLine("Exception caught - "+e);
Console.WriteLine("Caught exception is thrown again");
//Throwning the caught exception
throw e;
}
}
}
Exception caught - System.IndexOutOfRangeException: Index was outside the bounds of the array.
at A.Main(String[] ar)
Caught exception is thrown again
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at A.Main(String[] ar)
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement