0% found this document useful (0 votes)
20 views

Chapter 3 - Exception Handling in VB

Uploaded by

kaleb123 shumu12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Chapter 3 - Exception Handling in VB

Uploaded by

kaleb123 shumu12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Event-Driven Programming

Chapter 3: Exception Handling

Event driving Programming by(VB) byDagne w . 1


Exception
 An exception is a problem that arises during the execution
of a program.
 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.
 Exception handling is built upon four keywords: try, catch,
finally, and throw.

Event driving Programming by(VB) byDagne w . 2


Exception
 Exception is a notification that something interrupts the
normal program execution.
 Exceptions provide a programming paradigm for detecting
and reacting to unexpected events.
 When an exception arises, the state of the program is
saved, the normal flow is interrupted and the control is
passed to an exception handler (if such exists in the current
context).
 Exceptions are raised or thrown by programming code that
must send a signal to the executing program about an error
or an unusual situation. For example, if we try to open a
file, which doesn’t exist, the code responsible for opening
the file will detect this and will throw an exception with a
proper error message.
Event driving Programming by(VB) byDagne w . 3
Exception
 An exception is unexpected error that occur when a
program is running.
❖ Examples:
 trying to read from a file that does not exist, throws
FileNotFoundException.
 Trying to read from a database table that does not exist,
throws a SqlException.
❖ Showing actual unhandled exceptions to the end user is
bad for two reasons
 Users will be annoyed as they are cryptic and does not
make much sense to the end users.
 Exceptions contain information, that can be used for
hacking into your application.
Event driving Programming by(VB) byDagne w . 4
Exception
 Exceptions in .NET are two types – system and application.
System exceptions are defined in .NET libraries and are
used by the framework, while application exceptions are
defined by application developers and are used by the
application software.
 When we, as developers, design our own exception classes,
it is a good practice to inherit from ApplicationException
and not directly from SystemException (or even worse –
directly from Exception). SystemException should only be
inherited internally within the .NET Framework.
 Some of the worst system exceptions include
ExecutionEngineException (which is thrown on internal
error within CLR), StackOverflowException (call-stack
overflow, most probably due to infinite recursion) and
OutOfMemoryException (insufficient
Event driving Programming by(VB) byDagne wmemory).
. 5
Exception
 An exception is actually a class that derives from
System.Exception class.
 The System.Exception class has several useful properties,
that provide valuable information about exception.
 Message: Gets a message that describes the current
exception
 Stack Trace: Provides the call stack to the line number in
the method where the exception occurred.
 Source: gets or sets the name of the application or object
that causes the error.
 ToString(): creates and return a string representation of the
current exception

Event driving Programming by(VB) byDagne w . 6


Exception
 Exceptions are represented by classes. The exception
classes in VB 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.
 TheSystem.ApplicationException class supports exceptions
generated by application programs. Hence 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 −
Event driving Programming by(VB) byDagne w . 7
Exception

Event driving Programming by(VB) byDagne w . 8


Catching and Handling Exceptions
 We use try, catch and finallyblocks for exception handling:
 try: The code that can possibly cause an exception will be in
the try block.
 Catch: Handles the exception.
 Finally: Clean and free resources that the class was holding
onto during the program execution. Finallyblock is
optional.
 Note: it is a good practice to always release resources in the
finally block, because finally block is guaranteed to
execute, irrespective of whether there is an exception or
not. Specific exceptions will be caught before the base
general exception, so specific exception blocks should
always be on top of the base exception block. Otherwise,
you will encounter a compiler error
Event driving Programming by(VB) byDagne w . 9
Catching and Handling Exceptions
 try − A try block identifies a block of code for which
particular exceptions is activated. It is 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.
Event driving Programming by(VB) byDagne w . 10
Catching and Handling Exceptions
 Exception handling is a mechanism, which allows
exceptions to be thrown and caught.
 This mechanism is provided internally by the CLR
(Common Language Runtime).
 Parts of the exception handling infrastructure are the
language constructs in C# for throwing and catching
exceptions. CLR takes care to propagate each exception to
the code that can handle it.
 To handle an exception, we must surround the code that
could throw an exception with a try-catch block

Event driving Programming by(VB) byDagne w . 11


Exception Syntax
 Assuming a block raises 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
' Code that might cause an exception
Catch ex As ExceptionType
' Code to handle the exception
Finally
' Code that will always run, regardless of an exception
End Try
Event driving Programming by(VB) byDagne w . 12
DivideByZeroException

This exception is thrown when there is an attempt to divide by zero


Try
' Code that may cause an exception
Dim result As Integer = 10 / 0
Catch ex As DivideByZeroException
' Handle specific exception
Console.WriteLine("Cannot divide by zero!")
Catch ex As Exception
' Handle any other exceptions
Console.WriteLine("An error occurred: " & ex.Message)
Finally
' Code that runs after the try or catch block, whether or not an exception was
thrown
Console.WriteLine("Execution completed.")
End Try
Event driving Programming by(VB) byDagne w . 13
OutOfMemoryException
This exception is thrown when there is not enough
memory to continue the execution of a program.
Try
Dim largeArray(1000000000) As Byte
Catch ex As OutOfMemoryException
Console.WriteLine("Error: " & ex.Message)
End Try

Event driving Programming by(VB) byDagne w . 14


IndexOutOfRangeException
This exception is thrown when an attempt is made to
access an element of an array or collection with an
index that is outside its bounds.
Dim numbers() As Integer = {1, 2, 3}
Try
Dim number As Integer = numbers(5)
Catch ex As IndexOutOfRangeException
Console.WriteLine("Error: " & ex.Message)
End Try

Event driving Programming by(VB) byDagne w . 15


FormatException
This exception is thrown when the format of an
argument does not meet the parameter
specifications of the invoked method
Try
Dim num As Integer =
Integer.Parse("NotANumber")
Catch ex As FormatException
Console.WriteLine("Error: " & ex.Message)
End Try

Event driving Programming by(VB) byDagne w . 16


NullReferenceException

This exception is thrown when there is an attempt to


dereference a null object reference
Try
Dim obj As Object = Nothing
Console.WriteLine(obj.ToString())
Catch ex As NullReferenceException
Console.WriteLine("Error: " & ex.Message)
End Try

Event driving Programming by(VB) byDagne w . 17


IOException

This exception is thrown when an I/O error occurs


Imports System.IO
Try
Dim reader As StreamReader =
File.OpenText("nonexistentfile.txt")
Catch ex As IOException
Console.WriteLine("Error: " & ex.Message)
End Try

Event driving Programming by(VB) byDagne w . 18


ArgumentOutOfRangeException
This exception is thrown when an argument is outside the allowable range
of values.
Sub CheckAge(age As Integer)
If age < 0 OrElse age > 120 Then
Throw New ArgumentOutOfRangeException(NameOf(age), "Age
must be between 0 and 120.")
End If
Console.WriteLine("Age is valid.")
End Sub
Try
CheckAge(130)
Catch ex As ArgumentOutOfRangeException
Console.WriteLine("Error: " & ex.Message)
End Try
Event driving Programming by(VB) byDagne w . 19
Exercises
 Find out all exceptions in the System.IO.IOException
hierarchy.
 Find out all standard exceptions that are part of the
hierarchy holding the class
System.IO.FileNotFoundException.
 Find out all standard exceptions from
System.ApplicationException hierarchy.
 Explain the concept of exceptions and exception handling,
when they are used and how to catch exceptions.
 Explain when the statement try-finally is used. Explain the
relationship between the statements try-finally and using.
 Explain the advantages when using exceptions.

Event driving Programming by(VB) byDagne w . 20


THANK YOU!!

Event driving Programming by(VB) byDagne w . 21

You might also like