KEMBAR78
Introduction of exception in vb.net
Introduction of Exception
By Lecturer Suraj Pandey CCT College
Exception are just runtime errors, the terms exception handling
and error handling have becomes interchangeable. Exceptions
occur when running a program is running. We can trap such
exception and recover from them, rather than letting them bring
your program to an inglorious end.
By Lecturer Suraj Pandey CCT College
What is Exception
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.
By Lecturer Suraj Pandey CCT College
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.SystemException 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.
By Lecturer Suraj Pandey CCT College
The following table provides some of the predefined
exception classes derived from the Sytem.SystemException
class:
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
Unstructured Exception handling
Structured Exception handling
By Lecturer Suraj Pandey CCT College
Types of Exception handling
Structured Exception Handling
Structured exception handling tests specific pieces of the
code and, as exceptions occur, adapts your exception-
handling code to the circumstances that caused the
exception. It is significantly faster in large applications than
unstructured exception handling and allows more flexible
response to errors as well as greater application reliability.
The Try...Catch...Finally control structure is fundamental
to structured exception handling. It tests a piece of code,
filters exceptions created by the execution of that code, and
reacts differently based on the type of thrown exception.
By Lecturer Suraj Pandey CCT College
The Try...Catch...Finally block
Try...Catch...Finally control structures test a piece of
code and direct how the application should handle various
categories of error. Each of the structure's three constituent
parts plays a specific role in this process.
By Lecturer Suraj Pandey CCT College
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
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
UNSTRUCTURED EXCEPTION
HANDLING
In unstructured exception handling, we place an On Error
GoTo statement at the beginning of a block of code, and it
handles any errors occurring within that block. When an
exception is raised in a procedure after the On Error GoTo
statement executes,the program branches to the line
argument specified in the On Error GoTo statement. The
line argument, which is a line number or line label, indicates
the exception handler location.
By Lecturer Suraj Pandey CCT College
Unstructured error handling using On Error GoTo can
degrade application performance and result in code that is
difficult to debug and maintain. Structured error handling is
the recommended method.
Syntax:
 On Error GoTo
The parts of this statement are as follow:
By Lecturer Suraj Pandey CCT College
a. On Error GoTo Line:
The On Error GoTo Line statement assumes that error-
handling code starts at the line specified in the required line
argument. If a run-time error occurs, control branches to the
line label or line number specified in the argument,
activating the error handler. The specified line must be in the
same procedure as the On Error GoTo Line statement;
otherwise, Visual Basic generates a compiler error.
We have to place an Exit Sub statement immediately before
the error-handling block. Otherwise, Visual Basic runs the
error-handling code when it reaches the end of the
subroutine, causing unwanted or unexpected results.By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
b. On Error Resume Next:
The On Error Resume Next statement specifies that in the
event of a run-time error control passes to the statement
immediately following the one in which the error occurred.
At that point, execution continues. On Error Resume Next
enables us to put error-handling routines where errors will
occur, rather than transferring control to another location in
the procedure.
Another variation on the Resume statement is Resume Line,
which is similar to On Error GoTo Line. Resume Line passes
control to a line we specify in the line argument. We can use
Resume Line only within an error handler
 Example:
 Module Module1
Sub Main()
Dim a, b, c As Integer
Console.WriteLine("Enter value for a:")
a = Console.ReadLine()
Console.WriteLine("Enter value for b:")
b = Console.ReadLine()
On Error GoTo Errorhandler
c = a / b
Console.WriteLine("Result: {0}", c)
Console.ReadKey()
Exit Sub
Errorhandler:
Console.WriteLine("You got an error")
Resume Next
 End Sub
End Module
c. On Error GoTo 0:
The On Error GoTo 0 statement disables any error handler
in the current procedure. If you do not include an On Error
GoTo 0 statement, the error handler is still disabled when
the procedure containing the exception handler ends.
d. On Error GoTo -1:
The On Error GoTo -1 statement disables any exception
handlers in the current procedure. If you do not include an
On Error GoTo -1 statement, the exception is automatically
disabled when its procedure ends.
By Lecturer Suraj Pandey CCT College
Raising an Exception Intentionally
There are cases in programs where you might want to create
an exception because, although no visual basic trappable
exception has occurred, some situation may have occurred
that’s incompatible with your program’s logic. You can
create an exception intentionally raising an exception, with
the visual basic Err object’s Raise method, which is declared
this way internally in VB.NET:
Raise(ByVal Number As Integer, Optional ByVal Source As
Object= Nothing, Optional ByVal Description As object=
Nothing, optional ByVal HelpFile As object= Nothing
Optional ByVal HelpContext As Object=Nothing)
By Lecturer Suraj Pandey CCT College
Here are the arguments for the Raise method:
Number --- Long integer that identifies the nature of the
exception
Source --- String expression naming the object or application
that generated the exception, use the form project.class
Description --- String expression describing the exception
Helpfile --- The path to the help file in which help on this
exception can be found
Helpcontext --- A context ID identifying a topic within
helpfile that provides help for the exception.
By Lecturer Suraj Pandey CCT College
Example, here lets generate our own
exception, exception number 51:
By Lecturer Suraj Pandey CCT College
Exception filtering in the catch
block
When you’re handling exceptions you usually want to handle
different types of exceptions differently, according to the
nature of the exception that occurred. This process is called
filtering.
 We can filter on specific classes of exceptions, which means
you have to prepare for the various exceptions you want to
handle.
Exceptions are based on the visual basic exception class
(which, like all other objects in visual basic, is based on the
object class)
By Lecturer Suraj Pandey CCT College
The derived class itself has many derived classes, the
overflowException class, which is based on the
ArithmeticException class, which is based on the
SystemException class, which is based on the Exception
class:
System.Object
System.Exception
System.SystemException
System.ArithmeticException
System.OverflowException
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
USING MULTIPLE CATCH
STATEMENTS
You also can use multiple catch statements when you filter
exceptions. Here’s an example that specifically handles
overflow, invalid argument, and argument out of range
exceptions:
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
If you want to add a general exception handler to catch any
exceptions not filtered, you can add a catch block for the
Exception class at the end of the other Catch blocks:
By Lecturer Suraj Pandey CCT College
By Lecturer Suraj Pandey CCT College
The code in the Finally block, if there is one, is always executed
in a Try…. Catch…..Finally statement, even if there was no
exception, and even if you execute an Exit Try statement. This
allows you to deallocate resources and so on. Here’s an example
with a Finally block.
By Lecturer Suraj Pandey CCT College
Use Finally
 Module Module1
Sub main()
Dim int1=0, int2=1, int3 As Integer
Try
int3=int2/int1
System.console.writeline(“The answer is {0}”, int3)
Catch e As System.OverflowException
System.console.WriteLine(“Exception: Arithmetic Overflow!”)
Catch e As System.ArgumentException
System.console.WriteLine(“Exception: Invalid argument value!”)
Catch e As System.ArgumentOutofRangeException
System.console.WriteLine(“Exception: Argument out of range!”)
Finally
System.console.WriteLine(“Execution of sensitive code” & “is complete” )
End Try
End Sub
End Module
By Lecturer Suraj Pandey CCT College
Exception: Arithmetic overflow!
Execution of sensitive code is complete
By Lecturer Suraj Pandey CCT College
 We can throw an exception using the Throw statement, and we can
also rethrow a caught exception using the Throw statement. Here’s an
example where we can explicitly throw an overflow exception:
 Module Modul1
Sub Main()
Try
Throw New OverflowException()
Catch e As Exception
System.console.writeline(e.message)
End Try
End Sub
By Lecturer Suraj Pandey CCT College
Throwing an Exception
The .NET Framework provides a hierarchy of exception classes
ultimately derived from the base class Exception. Each of these
classes defines a specific exception, so in many cases we only
have to catch the exception. We can also create our own
exception classes by deriving from the Exception class.
When creating our own exceptions, it is good coding practice to
end the class name of the user-defined exception with the word
"Exception."
By Lecturer Suraj Pandey CCT College
Throwing a Custom Exception
Module Module1
Sub Main()
Try
Throw New ApplicationException(“This is a new
exception”)
Catch e As Exception
System.console.WriteLine(e.Message)
End Try
End Sub
End Module
By Lecturer Suraj Pandey CCT College

Introduction of exception in vb.net

  • 1.
    Introduction of Exception ByLecturer Suraj Pandey CCT College
  • 2.
    Exception are justruntime errors, the terms exception handling and error handling have becomes interchangeable. Exceptions occur when running a program is running. We can trap such exception and recover from them, rather than letting them bring your program to an inglorious end. By Lecturer Suraj Pandey CCT College What is Exception
  • 3.
    An exception isa 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. By Lecturer Suraj Pandey CCT College
  • 4.
    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.SystemException 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. By Lecturer Suraj Pandey CCT College
  • 5.
    The following tableprovides some of the predefined exception classes derived from the Sytem.SystemException class: By Lecturer Suraj Pandey CCT College
  • 6.
    By Lecturer SurajPandey CCT College
  • 7.
    Unstructured Exception handling StructuredException handling By Lecturer Suraj Pandey CCT College Types of Exception handling
  • 8.
    Structured Exception Handling Structuredexception handling tests specific pieces of the code and, as exceptions occur, adapts your exception- handling code to the circumstances that caused the exception. It is significantly faster in large applications than unstructured exception handling and allows more flexible response to errors as well as greater application reliability. The Try...Catch...Finally control structure is fundamental to structured exception handling. It tests a piece of code, filters exceptions created by the execution of that code, and reacts differently based on the type of thrown exception. By Lecturer Suraj Pandey CCT College
  • 9.
    The Try...Catch...Finally block Try...Catch...Finallycontrol structures test a piece of code and direct how the application should handle various categories of error. Each of the structure's three constituent parts plays a specific role in this process. By Lecturer Suraj Pandey CCT College
  • 10.
    Try: A Tryblock 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 By Lecturer Suraj Pandey CCT College
  • 11.
    By Lecturer SurajPandey CCT College
  • 12.
    By Lecturer SurajPandey CCT College
  • 13.
    By Lecturer SurajPandey CCT College
  • 14.
    By Lecturer SurajPandey CCT College
  • 15.
    By Lecturer SurajPandey CCT College
  • 16.
    UNSTRUCTURED EXCEPTION HANDLING In unstructuredexception handling, we place an On Error GoTo statement at the beginning of a block of code, and it handles any errors occurring within that block. When an exception is raised in a procedure after the On Error GoTo statement executes,the program branches to the line argument specified in the On Error GoTo statement. The line argument, which is a line number or line label, indicates the exception handler location. By Lecturer Suraj Pandey CCT College
  • 17.
    Unstructured error handlingusing On Error GoTo can degrade application performance and result in code that is difficult to debug and maintain. Structured error handling is the recommended method. Syntax:  On Error GoTo The parts of this statement are as follow: By Lecturer Suraj Pandey CCT College
  • 18.
    a. On ErrorGoTo Line: The On Error GoTo Line statement assumes that error- handling code starts at the line specified in the required line argument. If a run-time error occurs, control branches to the line label or line number specified in the argument, activating the error handler. The specified line must be in the same procedure as the On Error GoTo Line statement; otherwise, Visual Basic generates a compiler error. We have to place an Exit Sub statement immediately before the error-handling block. Otherwise, Visual Basic runs the error-handling code when it reaches the end of the subroutine, causing unwanted or unexpected results.By Lecturer Suraj Pandey CCT College
  • 19.
    By Lecturer SurajPandey CCT College
  • 20.
    b. On ErrorResume Next: The On Error Resume Next statement specifies that in the event of a run-time error control passes to the statement immediately following the one in which the error occurred. At that point, execution continues. On Error Resume Next enables us to put error-handling routines where errors will occur, rather than transferring control to another location in the procedure. Another variation on the Resume statement is Resume Line, which is similar to On Error GoTo Line. Resume Line passes control to a line we specify in the line argument. We can use Resume Line only within an error handler
  • 21.
     Example:  ModuleModule1 Sub Main() Dim a, b, c As Integer Console.WriteLine("Enter value for a:") a = Console.ReadLine() Console.WriteLine("Enter value for b:") b = Console.ReadLine() On Error GoTo Errorhandler c = a / b Console.WriteLine("Result: {0}", c) Console.ReadKey() Exit Sub Errorhandler: Console.WriteLine("You got an error") Resume Next  End Sub End Module
  • 22.
    c. On ErrorGoTo 0: The On Error GoTo 0 statement disables any error handler in the current procedure. If you do not include an On Error GoTo 0 statement, the error handler is still disabled when the procedure containing the exception handler ends. d. On Error GoTo -1: The On Error GoTo -1 statement disables any exception handlers in the current procedure. If you do not include an On Error GoTo -1 statement, the exception is automatically disabled when its procedure ends. By Lecturer Suraj Pandey CCT College
  • 23.
    Raising an ExceptionIntentionally There are cases in programs where you might want to create an exception because, although no visual basic trappable exception has occurred, some situation may have occurred that’s incompatible with your program’s logic. You can create an exception intentionally raising an exception, with the visual basic Err object’s Raise method, which is declared this way internally in VB.NET: Raise(ByVal Number As Integer, Optional ByVal Source As Object= Nothing, Optional ByVal Description As object= Nothing, optional ByVal HelpFile As object= Nothing Optional ByVal HelpContext As Object=Nothing) By Lecturer Suraj Pandey CCT College
  • 24.
    Here are thearguments for the Raise method: Number --- Long integer that identifies the nature of the exception Source --- String expression naming the object or application that generated the exception, use the form project.class Description --- String expression describing the exception Helpfile --- The path to the help file in which help on this exception can be found Helpcontext --- A context ID identifying a topic within helpfile that provides help for the exception. By Lecturer Suraj Pandey CCT College
  • 25.
    Example, here letsgenerate our own exception, exception number 51: By Lecturer Suraj Pandey CCT College
  • 26.
    Exception filtering inthe catch block When you’re handling exceptions you usually want to handle different types of exceptions differently, according to the nature of the exception that occurred. This process is called filtering.  We can filter on specific classes of exceptions, which means you have to prepare for the various exceptions you want to handle. Exceptions are based on the visual basic exception class (which, like all other objects in visual basic, is based on the object class) By Lecturer Suraj Pandey CCT College
  • 27.
    The derived classitself has many derived classes, the overflowException class, which is based on the ArithmeticException class, which is based on the SystemException class, which is based on the Exception class: System.Object System.Exception System.SystemException System.ArithmeticException System.OverflowException By Lecturer Suraj Pandey CCT College
  • 28.
    By Lecturer SurajPandey CCT College
  • 29.
    By Lecturer SurajPandey CCT College
  • 30.
    USING MULTIPLE CATCH STATEMENTS Youalso can use multiple catch statements when you filter exceptions. Here’s an example that specifically handles overflow, invalid argument, and argument out of range exceptions: By Lecturer Suraj Pandey CCT College
  • 31.
    By Lecturer SurajPandey CCT College
  • 32.
    If you wantto add a general exception handler to catch any exceptions not filtered, you can add a catch block for the Exception class at the end of the other Catch blocks: By Lecturer Suraj Pandey CCT College
  • 33.
    By Lecturer SurajPandey CCT College
  • 34.
    The code inthe Finally block, if there is one, is always executed in a Try…. Catch…..Finally statement, even if there was no exception, and even if you execute an Exit Try statement. This allows you to deallocate resources and so on. Here’s an example with a Finally block. By Lecturer Suraj Pandey CCT College Use Finally
  • 35.
     Module Module1 Submain() Dim int1=0, int2=1, int3 As Integer Try int3=int2/int1 System.console.writeline(“The answer is {0}”, int3) Catch e As System.OverflowException System.console.WriteLine(“Exception: Arithmetic Overflow!”) Catch e As System.ArgumentException System.console.WriteLine(“Exception: Invalid argument value!”) Catch e As System.ArgumentOutofRangeException System.console.WriteLine(“Exception: Argument out of range!”) Finally System.console.WriteLine(“Execution of sensitive code” & “is complete” ) End Try End Sub End Module By Lecturer Suraj Pandey CCT College
  • 36.
    Exception: Arithmetic overflow! Executionof sensitive code is complete By Lecturer Suraj Pandey CCT College
  • 37.
     We canthrow an exception using the Throw statement, and we can also rethrow a caught exception using the Throw statement. Here’s an example where we can explicitly throw an overflow exception:  Module Modul1 Sub Main() Try Throw New OverflowException() Catch e As Exception System.console.writeline(e.message) End Try End Sub By Lecturer Suraj Pandey CCT College Throwing an Exception
  • 38.
    The .NET Frameworkprovides a hierarchy of exception classes ultimately derived from the base class Exception. Each of these classes defines a specific exception, so in many cases we only have to catch the exception. We can also create our own exception classes by deriving from the Exception class. When creating our own exceptions, it is good coding practice to end the class name of the user-defined exception with the word "Exception." By Lecturer Suraj Pandey CCT College Throwing a Custom Exception
  • 39.
    Module Module1 Sub Main() Try ThrowNew ApplicationException(“This is a new exception”) Catch e As Exception System.console.WriteLine(e.Message) End Try End Sub End Module By Lecturer Suraj Pandey CCT College