SlideShare a Scribd company logo
1 of 39
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

More Related Content

What's hot

Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCoCode Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
Evgeny Mandrikov
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
sotlsoc
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
helpido9
 

What's hot (19)

Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAUTest Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
 
Code Review
Code ReviewCode Review
Code Review
 
Introducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationIntroducing Keyword-driven Test Automation
Introducing Keyword-driven Test Automation
 
Introducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test AutomationIntroducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test Automation
 
Code Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCoCode Coverage Revised : EclEmma on JaCoCo
Code Coverage Revised : EclEmma on JaCoCo
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
How to improve code quality for iOS apps?
How to improve code quality for iOS apps?How to improve code quality for iOS apps?
How to improve code quality for iOS apps?
 
Testing Java applications with Maveryx
Testing Java applications with MaveryxTesting Java applications with Maveryx
Testing Java applications with Maveryx
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
 
Code review
Code reviewCode review
Code review
 
.Net Debugging Techniques
.Net Debugging Techniques.Net Debugging Techniques
.Net Debugging Techniques
 
Aspect-Oriented Programming and Depedency Injection
Aspect-Oriented Programming and Depedency InjectionAspect-Oriented Programming and Depedency Injection
Aspect-Oriented Programming and Depedency Injection
 
Software Quality via Unit Testing
Software Quality via Unit TestingSoftware Quality via Unit Testing
Software Quality via Unit Testing
 
Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6Cis 355 i lab 1 of 6
Cis 355 i lab 1 of 6
 
Java basics training 1
Java basics training 1Java basics training 1
Java basics training 1
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
 
Robot framework
Robot frameworkRobot framework
Robot framework
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 

Similar to Introduction of exception in vb.net

Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
Alpesh Oza
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
Vince Vo
 

Similar to Introduction of exception in vb.net (20)

6-Error Handling.pptx
6-Error Handling.pptx6-Error Handling.pptx
6-Error Handling.pptx
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Exception handling
Exception handlingException handling
Exception handling
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Exceptions
ExceptionsExceptions
Exceptions
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

More from suraj pandey

More from suraj pandey (20)

Systemcare in computer
Systemcare in computer Systemcare in computer
Systemcare in computer
 
vb.net Constructor and destructor
vb.net Constructor and destructorvb.net Constructor and destructor
vb.net Constructor and destructor
 
Overloading and overriding in vb.net
Overloading and overriding in vb.netOverloading and overriding in vb.net
Overloading and overriding in vb.net
 
Basic in Computernetwork
Basic in ComputernetworkBasic in Computernetwork
Basic in Computernetwork
 
Computer hardware
Computer hardwareComputer hardware
Computer hardware
 
Dos commands new
Dos commands new Dos commands new
Dos commands new
 
History of computer
History of computerHistory of computer
History of computer
 
Dos commands
Dos commandsDos commands
Dos commands
 
Basic of Internet&email
Basic of Internet&emailBasic of Internet&email
Basic of Internet&email
 
Basic fundamental Computer input/output Accessories
Basic fundamental Computer input/output AccessoriesBasic fundamental Computer input/output Accessories
Basic fundamental Computer input/output Accessories
 
Transmission mediums in computer networks
Transmission mediums in computer networksTransmission mediums in computer networks
Transmission mediums in computer networks
 
Introduction to vb.net
Introduction to vb.netIntroduction to vb.net
Introduction to vb.net
 
Introduction to computer
Introduction to computerIntroduction to computer
Introduction to computer
 
Computer Fundamental Network topologies
Computer Fundamental Network topologiesComputer Fundamental Network topologies
Computer Fundamental Network topologies
 
Basic of Computer software
Basic of Computer softwareBasic of Computer software
Basic of Computer software
 
Basic using of Swing in Java
Basic using of Swing in JavaBasic using of Swing in Java
Basic using of Swing in Java
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 
Generics in java
Generics in javaGenerics in java
Generics in java
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 

Introduction of exception in vb.net

  • 1. Introduction of Exception By Lecturer Suraj Pandey CCT College
  • 2. 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
  • 3. 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
  • 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 table provides some of the predefined exception classes derived from the Sytem.SystemException class: By Lecturer Suraj Pandey CCT College
  • 6. By Lecturer Suraj Pandey CCT College
  • 7. Unstructured Exception handling Structured Exception handling By Lecturer Suraj Pandey CCT College Types of Exception handling
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. By Lecturer Suraj Pandey CCT College
  • 12. By Lecturer Suraj Pandey CCT College
  • 13. By Lecturer Suraj Pandey CCT College
  • 14. By Lecturer Suraj Pandey CCT College
  • 15. By Lecturer Suraj Pandey CCT College
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. By Lecturer Suraj Pandey CCT College
  • 20. 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
  • 21.  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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. Example, here lets generate our own exception, exception number 51: By Lecturer Suraj Pandey CCT College
  • 26. 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
  • 27. 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
  • 28. By Lecturer Suraj Pandey CCT College
  • 29. By Lecturer Suraj Pandey CCT College
  • 30. 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
  • 31. By Lecturer Suraj Pandey CCT College
  • 32. 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
  • 33. By Lecturer Suraj Pandey CCT College
  • 34. 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
  • 35.  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
  • 36. Exception: Arithmetic overflow! Execution of sensitive code is complete By Lecturer Suraj Pandey CCT College
  • 37.  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
  • 38. 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
  • 39. 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