Minifycode 2022-05-12 Viewed 1.4K times C#

Exception Classes in C#


In this article, you will learn what is exception handling in c#, c# exceptions are represented by classes. The exception classes in C# are directly or indirectly derived from the System.Exception class. 
Some of the exception classes derived from the System.Exception class are the System.SystemException classes and System.ApplicationException.

The System.ApplicationException class supports exceptions generated by application programs. So, the exceptions defined by the programmers
 should derive from this class.

The System.SystemException class is the base class for all predefined system exception.

The following table provides some of the predefined exception classes derived from the Sytem.SystemException class

Errors refer to the mistake or faults which occur during program development or execution. 
If you don't find them and correct them, they cause a program to produce wrong results.

Types of Errors
In programming language errors can be divided into three categories as given below-

Syntax Errors
Syntax errors occur during development, when you make type mistake in code.
 For example, instead of writing while, you write WHILE then it will be a syntax error since C# is a case sensitive language.

bool flag=true;

FOR (int i=0;i<=10;i++) //syntax error, c# is case sensitive
{
 //TO DO:
}


Runtime Errors (Exceptions)


Runtime errors occur during execution of the program. These are also called exceptions. 
This can be caused due to improper user inputs, improper design logic or system errors.

int a = 7, b = 0;
int result = a / b; // Divide By Zero Exception


Exceptions can be handled by using try-catch blocks.

Logical Errors


Logic errors occur when the program is written fine but it does not produce desired result. 
Logic errors are difficult to find because you need to know for sure that the result is wrong

int a = 7, b = 9;
double avg = a + b / 3.0; // logical error, it should be (a + b) / 3.0


Exception Handling


Exception handling is a mechanism to detect and handle run time errors. 
It is achieved by using Try-Catch-Finally blocks and throw keyword.


Try block


The try block encloses the statements that might throw an exception.

try
{
 // Statements that can cause exception.
}


Catch block


Catch block handles any exception if a exists.

catch(ExceptionType e)
{
 // Statements to handle exception.
}


Finally block


The finally block can be used for doing any clean-up process like releasing unused resources even if an exception is thrown.
 For example, disposing database connection.

finally
{
 // Statement to clean up.
}


Throw keyword


This keyword is used to throw an exception explicitly.

catch (Exception e)
{
 throw (e);
}


Key points about exceptions handling

  • Exceptions are types that all directly or indirectly derive from System.Exception class.
  • Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.
  • A try block is used to throw multiple exceptions that can handle by using multiple catch blocks.
  • More specialized catch block should come before a generalized one. Otherwise specialized catch block will never be executed.
  • Exceptions can be explicitly generated by a program by using the throw keyword.
  • If no exception handling mechanism is used, the program stops executing with an error message.
  • By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block.
Catch
{
 Console.WriteLine("Exception");
}


By providing a catch block with an exception object, you can obtain more information about the type of exception that occurred.

catch(Exception e)
{
 Console.WriteLine(e.Message);
}

 


The statements inside the finally block are always executed whether exception occurs or not in the program.

Also, before the termination of the program finally block is always executed.

Order of Try-Catch-Finally blocks


In the order of exceptions handling blocks try block comes first, after that catch block(s) come and in the last finally block come.

try
{
 // statements that can cause exception.
}
catch (MoreSpecificExceptionType e1)
{
 // error handling code
}
catch (SpecificExceptionType e2)
{
 // error handling code
}
catch (GeneralExceptionType e3)
{
 // error handling code
}
finally
{
 // statement to clean up.
} 


You can also skip finally block if required.

try
{
 // statements that can cause exception.
}
catch (MoreSpecificExceptionType e1)
{
 // error handling code
}
catch (SpecificExceptionType e2)
{
 // error handling code
}
catch (GeneralExceptionType eN)
{
 // error handling code
} 

You can also skip catch block(s) if required.

try
{
 // statements that can cause exception.
}
finally
{
 // statement to clean up.
}

Example....

using System;

namespace ErrorHandlingApplication {
   class DivNumbers {
      int result;
      
      DivNumbers() {
         result = 0;
      }
      public void division(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.division(27, 0);
         Console.ReadKey();
      }
   }
}

So, combination of try-catch-finally or try-catch or try-finally blocks is valid.

 

C# - Exception Handling - C# exceptions handling are represented by classes. The exception classes in C# are directly or indirectly derived from the System.Exception class.
C# is a programming language developed by Microsoft that runs on the .NET Framework. C# is used to develop web, desktop, mobile, games and much more application. C# is a object-oriented programming language developed by Microsoft within its .NET Framework. Led by Anders Hejlsberg, your basic C# programming and will also take you through various advanced concepts related to C# programming language. C# such as control statements, objects and classes, inheritance, constructor, destructor, this, static, sealed, polymorphism, abstraction, abstract class, interface, File IO, Collections, namespace, encapsulation, properties, indexer, arrays, strings, regex, exception handling, multithreading etc. For example... using System; namespace MinifyCode { class Program { static void Main(string[] args) { Console.WriteLine("Hello Minify Code"); } } } Output: Hello Minify Code In this article you will learn, what is server side controls. We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object. Session Application Cache Request Response Server User Trace Server Object The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform many type of jobs. Methods and Properties of the Server object The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using System.Web.SessionState; using System.Data.Entity; namespace minifycode { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Initialize the product database. Database.SetInitializer(new ProductDatabaseInitializer()); // Create custom role and user. RoleActions roleActions = new RoleActions(); roleActions.AddUserAndRole(); // Add Routes. RegisterCustomRoutes(RouteTable.Routes); } void RegisterCustomRoutes(RouteCollection routes) { routes.MapPageRoute( "ProductsCategoryRoute", "Category/{categoryName}", "~/ProductList.aspx" ); routes.MapPageRoute( "ProductNameRoute", "Product/{productName}", "~/ProductDetails.aspx" ); } } }