C# Exception

In this chapter you will learn:

  1. What is Exception
  2. System exceptions

Description

An exception is an error that occurs at runtime.


using System;/* ww w  .ja  va2s  . co  m*/

class MainClass{
    
    public static void Main(){
        int Zero = 0;
        try {
            int j = 22 / Zero;
        } catch (DivideByZeroException e) // catch a specific exception
        {
            Console.WriteLine("DivideByZero {0}", e);
        } catch (Exception e)// catch any remaining exceptions
        {
            Console.WriteLine("Exception {0}", e);
        }
    }
}

The code above generates the following result.

System exceptions

In C#, exceptions are represented by classes. All exception classes must be derived from the built-in exception class System.Exception.

SystemException class and ApplicationException class are derived from System.Exception. SystemException support exceptions generated by the C# runtime system (that is, the Common Language Runtime).

ApplicationException support exceptions generated by application programs. SystemException and ApplicationException add nothing to Exception. SystemException and ApplicationException define the tops of two different exception hierarchies.

Next chapter...

What you will learn in the next chapter:

  1. Predefined Exception classes
  2. Example for C# Exception
Home »
  C# Tutorial »
    C# Language »
      C# Exception
C# Exception
C# Exception classes
C# try Statements and Exceptions
C# catch Clause
C# finally Block
C# throw statement
C# System Exception