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

Exception Handling 2023

Exception handling allows code to gracefully handle errors or unexpected situations that occur during program execution known as exceptions. It uses keywords like Try, Catch, Finally and Throw to identify blocks of code that may throw exceptions and to specify how the program should respond by catching and handling exceptions. This prevents programs from crashing when errors occur and allows execution to continue.

Uploaded by

freestadiumtix
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)
22 views

Exception Handling 2023

Exception handling allows code to gracefully handle errors or unexpected situations that occur during program execution known as exceptions. It uses keywords like Try, Catch, Finally and Throw to identify blocks of code that may throw exceptions and to specify how the program should respond by catching and handling exceptions. This prevents programs from crashing when errors occur and allows execution to continue.

Uploaded by

freestadiumtix
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/ 21

4.3.

3 Exception handling

“Only perfect programmers create perfect code


from the beginning.
The rest must address imperfections along the way
to developing a successful application.”
*
Exception handling

• Show understanding of an exception and the importance of


exception handling
• Show understanding of when it is appropriate to use exception
handling
• Write code to use exception handling in practical programming
* Exception handling
Example, when your application asks the user to input a telephone
number, the following assumptions come into play:

• The user will input a number rather than characters.


• The number will have a certain format.
• The user will not input a null string.
• The user has a single telephone number.

User input might violate any or all of these assumptions.


Robust code requires adequate exception handling, which allows your
application to recover gracefully from such a violation.
*
VB.Net - Exception Handling
• 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.
*
Runtime errors are a lot harder than Design Time errors to track down.
As their name suggests, these errors occur when the programme is
running.
Runtime errors are the ones that crash your programme.
A simple way to crash a programme is to divide by zero.
Dim Num1 As Integer Sub main()
Dim Num2 As Integer Dim Num1 As Integer
Dim Answer as Single Dim Num2 As Integer
Dim answer As Single
Num1 = 10 Num1 = 10
Num2 = 0 Num2 = 0
Answer = CInt(Num1 / Num2)
answer = CInt(Num1 / Num2)
Console.WriteLine(answer)
Console.ReadKey()
End Sub
What happens is that you'll get the following error message popping up:
*
If the error occurred in a normal program, it would shut down.
Not something you want a program to do in mid stream!
So how to deal with it?
Sub main()
*
Try
Dim Num1 As Integer
Dim Num2 As Integer
Dim answer As Single
Num1 = 10
Num2 = 0

answer = CInt(Num1 / Num2)


Console.WriteLine(answer)
Console.ReadKey()
Catch ex As Exception
Console.WriteLine("Divide by zero error")
Console.ReadKey()
End Try
End Sub
VB.NET has a inbuilt class that deals with errors.
The Class is called Exception.
When an exception error is found, an Exception object is created.
The coding structure VB.NET uses to deal with such Exceptions is
called the Try … Catch structure.

In the coding, type the word Try.


Then hit the return key on your keyboard.
VB.NET completes the rest of the structure for you:
Try The Try word means "Try to execute this code".

Catch ex As Exception The Catch word means "Catch any errors here".

End Try The ex is a variable, and the type of variable it is an Exception


object.
When designing and writing program code, explain what is meant by:
• an exception
• exception handling
Exception:

1. situation causing a crash / run-time error / fatal error 1

Exception handling:

2. code which is called when a run-time error occurs 1


3. … to avoid the program terminating/crashing
c) 1 Open a non-existent file
2 Directory path does not exist
3 Attempt to read past the end of the file // attempt to read an empty file
4 Array subscript is out of range
5 Non-integer value / corrupt data read
6 File already open in a different mode // wrong file permissions
VB.Net - Exception Handling
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.
VB.Net - Exception Handling

Syntax

Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
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
An example of throwing an exception when dividing by zero condition occurs:
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
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
Module
You exceptionProg
can use a throw statement in the catch block to throw the present object as:
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