0% found this document useful (0 votes)
6 views14 pages

Exception Report

The document discusses exception handling in .NET, defining exceptions as errors encountered during program execution that can be handled or cause termination. It outlines the advantages of .NET's exception handling over traditional methods, introduces key concepts like Try, Catch, Finally, and Throw, and provides examples of common exception types and user-defined exceptions. Additionally, it explains the structure of exception classes in the .NET Framework and demonstrates how to create and throw exceptions.

Uploaded by

Rusher Gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views14 pages

Exception Report

The document discusses exception handling in .NET, defining exceptions as errors encountered during program execution that can be handled or cause termination. It outlines the advantages of .NET's exception handling over traditional methods, introduces key concepts like Try, Catch, Finally, and Throw, and provides examples of common exception types and user-defined exceptions. Additionally, it explains the structure of exception classes in the .NET Framework and demonstrates how to create and throw exceptions.

Uploaded by

Rusher Gamer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

EXCEPTION

HANDLING
GROUP 3
Exceptions
An exception is any error condition or unexpected behavior that is
encountered by an executing programs. Exceptions can be thrown of
a fault in your code or in code that you call (sus as a shared library),
unavailable operating system resources, unexpected conditions that
the runtime encounters (such as code that can’t be verified), and so
on. Your application can recover from some of these conditions, but
not from others. Although you can recover from most application
exceptions, you can’t recover from most runtime exceptions.

In .NET, an exceptions is an object that inherits from the


System.Exceptions class. An exception is thrown from an area of code
where a problem has occurred. The exception is passed up the stack
until the application handles it or the program terminates.
Exceptions vs. tradition error-handling methods
Traditionally, a language’s error-handling model relied on either
the language’s unique way of detecting errors and location
handles for them, or on the error-handling mechanism provided
by the operating system. The way .NET implements exception
handling provides the following advantages:
 Exception throwing and handling works the same for .NET
programming languages.
 Doesn’t require any particular language syntax for handling
exceptions, but allows each language to define its own syntax.
 Exceptions can be thrown across process and even machine
boundaries.
 Exception handling code can be added to an application to
increase program reliability.
Exceptions offer advantages over
methods of error notification, such as
return codes. Failure don’t go
unnoticed because if an exception is
thrown and you don’t handle it, the
runtime terminates your application.
Invalid values don’t continue to
propagate through the system as a
result of code that fails to check for a
failure return code.
Exception type Description Example

Exception Common
Base class for all exceptions
None (use a derived class of this exception).
exceptions.

IndexOutOfRangeException Thrown by the runtime Indexing an array outside its valid range:
only when an array is arr[arr.Length+1]
indexed improperly.

NullReferenceException Thrown by the runtime object o = null;


only when a null object is o.ToString();
referenced.

InvalidOperationException Thrown by methods when Calling Enumerator.MoveNext() after removing an item


in an invalid state. from the underlying collection.

ArgumentException Base class for all argument None (use a derived class of this exception).
exceptions.

ArgumentNullException Thrown by methods that String s = null;


"Calculate".IndexOf(s);
do not allow an argument
to be null.
ArgumentOutOfRangeException Thrown by methods that String s = "string";
s.Substring(s.Length+1);
verify that arguments are
in a given range.
An exception is a problem that arises during the execution of a program.
An exception is a response to an exceptional circumstance that arises
while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program


to another. VB.Net exception handling is built upon four keywords
- Try, Catch, Finally and Throw.

 Try − A Try block identifies a block of code for which particular


exceptions will be activated. It's followed by one or more Catch blocks.

 Catch − A program catches an exception with an exception handler at


the place in a program where you want to handle the problem. The
Catch keyword indicates the catching of an exception.

 Finally − The Finally block is used to execute a given set of statements,


whether an exception is thrown or not thrown. For example, if you
open a file, it must be closed whether an exception is raised or not.

 Throw − A program throws an exception when a problem shows up.


This is done using a Throw keyword.
Syntax
 Assuming a block will raise an exception, a method catches an exception
using a combination of the Try and Catch keywords. A Try/Catch block is
placed around the code that might generate an exception. Code within a
Try/Catch block is referred to as protected code, and the syntax for using
Try/Catch looks like the following −
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
You can list down multiple catch statements to catch [ Finally
different type of exceptions in case your try block [ finallyStatements ] ]
raises more than one exception in different End Try
situations.
Exception Classes in .Net Framework
In the .Net Framework, exceptions are represented by classes.
The exception classes in .Net Framework are mainly directly
or indirectly derived from the System.Exception class. Some
of the exception classes derived from the System.Exception
class are
the System.ApplicationException and System.SystemExcepti
on classes.

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 −
Exception Class Description

System.IO.IOException Handles I/O errors.

Handles errors generated when a method refers to an array


System.IndexOutOfRangeException
index out of range.

Handles errors generated when type is mismatched with the


System.ArrayTypeMismatchException
array type.

System.NullReferenceException Handles errors generated from deferencing a null object.

Handles errors generated from dividing a dividend with


System.DivideByZeroException
zero.

System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles errors generated from insufficient free memory.

System.StackOverflowException Handles errors generated from stack overflow.


Handling Exceptions
VB.Net provides a structured solution to the
exception handling problems in the form of try and
catch blocks. Using these blocks the core program
statements are separated from the error-handling
statements. These error handling blocks are
implemented using
the Try, Catch and Finally keywords. Following is an
example of throwing an exception when dividing by
zero condition occurs −
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from the ApplicationException class.
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module

TempIsZeroException: Zero Temperature found


Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class.
You can use a throw statement in the catch block to throw the present object as −
Throw [ expression ]
The following program demonstrates this −

Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _ is
being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module

You might also like