Обработка исключений
Последнее обновление: 30.10.2015
В процессе выполнения программы нередко возникают такие ситуации, которые трудно или даже невозможно предусмотреть во время создания программы.
Например, при передаче файла по сети может неожиданно оборваться сетевое подключение. Такие ситуации называются исключениями.
Чтобы программа неожиданно не зависла в таких ситуациях, программисту нужно вводить в нее обработку исключений.
Для обработки исключений в языке VB.NET имеется конструкция Try…Catch..Finally. Ее использование выглядит следующим образом:
Sub Main() Dim a(3) As Integer Try a(5) = 3 Catch ex As Exception Console.WriteLine(ex.Message) Finally Console.WriteLine("Finally block") End Try Console.ReadLine() End Sub
В данном случае у нас как раз и возникает исключение, так как в массиве a только 4 элемента, а мы пытаемся присвоить значение шестому элементу.
При использовании блока Try…Catch..Finally сначала выполняются все инструкции между операторами Try и
Catch.
И если вдруг в каком-то месте кода возникает исключение, то обычный порядок выполнения кода останавливается и программа переходит к выражению Catch.
Это выражение имеет следующий синтаксис: Catch имя_переменной As тип_исключения
. В данном случае у нас объявляется переменная ex, которая
имеет тип Exception. При чем если возникшее исключение не является исключением типа, указанного в выражении Catch, то оно не обрабатывается,
а программа просто зависает или выбрасывает сообщение об ошибке. Так как тип Exception
является базовым типом для всех исключений, то в
выражении Catch ex As Exception
абсолютно все исключения.
В нашем случае мы просто выводим сообщение об исключении на экран с помощью свойства Message
, определенное в классе Exception
.
Далее в любом случае выполняется блок после оператора Finally
. Но этот блок необязательный, и его можно при обработке исключений опускать.
В случае, если в ходе программы исключений не возникнет, то программа не будет выполнять блок Catch, сразу перейдет к блоку Finally,
если он имеется.
Разработка собственных исключений
Мы можем создать свои собственные классы исключений, которые будут обрабатывать нежелательные ситуации. Для примера возьмем класс
Algorithm
, который мы сделали в одной из глав предыдущей части:
Public Class Algorithm Public Shared Function Factorial(x As Integer) As Integer If (x = 1) Then Return 1 Else Return x * Factorial(x - 1) End If End Function Public Shared Function Fibbonachi(x As Integer) As Integer If x = 0 Then Return 1 ElseIf x = 1 Then Return 1 Else Return Fibbonachi(x - 1) + Fibbonachi(x - 2) End If End Function End Class
Факториал и последовательность Фиббоначи определены только для положительных чисел, поэтому если мы передадим в функцию отрицательное число,
возникнет исключительная ситуация. Чтобы ее обработать и создадим класс NegativeNumberException
:
Public Class NegativeNumberException Inherits Exception Sub New() MyBase.New("В качестве параметра передано отрицательное число") End Sub End Class
В этом классе по сути мы только передаем сообщение в конструктор базового класса. Теперь вызовем обработку исключения в методе Factorial
с помощью ключевого слова Throw:
Public Shared Function Factorial(x As Integer) As Integer If x < 0 Then Throw New NegativeNumberException() If (x = 1) Then Return 1 Else Return x * Factorial(x - 1) End If End Function
И теперь, если мы передадим в этот метод отрицательные значения, в блоке Try...Catch
будет обрабатываться исключение NegativeNumberException
:
Try Console.WriteLine(Algorithm.Factorial(-1)) Catch ex As Exception Console.WriteLine(ex.Message) End Try
Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Операторы Try / Catch имеют следующий синтаксис:
Try [ try_Statement(s) ] [ Exit Try ] [ Catch [ exception_name [ As type ] ] [ When expression ] [ catch_Statement(s) ] [ Exit Try ] ] [ Catch ... ] [ Finally [ finally_Statement(s) ] ] End Try
Блок Try / Catch должен окружать код, который может вызвать исключение. Этот код известен как защищенный код. Вы можете использовать несколько операторов catch, когда вам нужно перехватить различные типы исключений.
С помощью операторов Try / Catch вы можете отделить ваш обычный программный код от Системы обработки ошибок. Давайте продемонстрируем, как обрабатывать исключение, используя ключевые слова Try, Catch и Наконец.
Шаг 1) Создайте новое консольное приложение.
Шаг 2) Используйте этот код:
Module Module1 Sub divisionFunction(ByVal n1 As Integer, ByVal n2 As Integer) Dim answer As Integer Try answer = n1 n2 Catch ex As DivideByZeroException Console.WriteLine("Exception: {0}", ex) Finally Console.WriteLine("Answer is: {0}", answer) End Try End Sub Sub Main() divisionFunction(4, 0) Console.ReadKey() End Sub End Module
Шаг 3) Нажмите кнопку «Пуск» на панели инструментов, чтобы выполнить код. Вы должны получить следующий вывод:
VB.NET позволяет вам определять ваши собственные исключения. Вы можете получить пользовательские классы исключений из класса ApplicationException. Давайте продемонстрируем это на примере:
Шаг 1) Создайте новое консольное приложение.
Шаг 2) Используйте следующий код:
Module Module1 Public Class HeightIsZeroException : Inherits ApplicationException Public Sub New(ByVal text As String) MyBase.New(text) End Sub End Class Public Class Height Dim height As Integer = 0 Sub showHeight() If (height = 0) Then Throw (New HeightIsZeroException("Zero Height found")) Else Console.WriteLine("Height is: {0}", height) End If End Sub End Class Sub Main() Dim hght As Height = New Height() Try hght.showHeight() Catch ex As HeightIsZeroException Console.WriteLine("HeightIsZeroException: {0}", ex.Message) End Try Console.ReadKey() End Sub End Module
Шаг 3) Нажмите кнопку «Пуск» в верхней панели, чтобы выполнить код. Вы должны получить следующий вывод:
In visual basic, Try Catch statement is useful to handle unexpected or runtime exceptions which will occur during execution of the program. The Try-Catch statement will contain a Try
block followed by one or more Catch
blocks to handle different exceptions.
In visual basic, whenever an exception occurred in the Try
block, then the CLR (common language runtime) will look for the catch
block that handles an exception. In case, if currently executing method does not contain such a Catch
block, then the CLR will display an unhandled exception message to the user and stops the execution of the program.
Visual Basic Try Catch Syntax
Following is the syntax of handling errors in visual basic using Try, Catch blocks.
Try
‘ Code that may cause exception
Catch ex As Exception
‘ Exception handling
End Try
As per the above syntax, the Try
block will contain the guarded code that may cause an exception so that if any errors occurred in our code, then immediately the code execution will be moved to Catch
block to handle those exceptions.
In Try-Catch statement, the Catch
block will execute only when an exception occurred in the code that is guarded by Try
block.
Visual Basic Try Catch Example
Following is the example of using Try-Catch statement in visual basic to handle the exceptions.
Module Module1
Sub Main(ByVal args As String())
Dim name As String = Nothing
Try
If name.Length > 0 Then ‘ Exception will occur
Console.WriteLine(«Name: « & name)
End If
Catch ex As Exception
Console.WriteLine(«Exception: {0}», ex.Message)
End Try
Console.ReadLine()
End Sub
End Module
If you observe the above code, we used Try
and Catch
blocks to handle runtime or unexpected errors during the execution of the program. Here, we wrote a code that may throw an exception inside of Try
block and in Catch
block we are handling the exception.
When we execute the above code, we will get the result as shown below.
Exception: Object reference not set to an instance of an object.
This is how we can use Try-Catch blocks to handle unexpected or runtime exceptions based on our requirements.
In visual basic, the Try
block must be followed by Catch
or Finally
or both blocks otherwise we will get a compile-time error.
Visual Basic Try with Multiple Catch Blocks
In the above Try-Catch statement example, we used only a single Catch
block with the Exception
base class argument to handle all the exceptions.
In case, if we want to handle a different type of exceptions in different ways, then we can specify multiple Catch
blocks with different exception types in the same Try-Catch statement and this process called an exception filtering.
If we define multiple Catch
blocks with a Try
statement, then the first Catch
statement that can handle an exception will be executed, any following Catch
statements that are even more compatible to handle an exception will be ignored so the order of Catch blocks must be always from most specific to least specific.
Following is the example of defining multiple catch blocks in a Try-Catch statement to handle different exceptions in different ways.
Module Module1
Sub Main(ByVal args As String())
Try
Console.WriteLine(«Enter x value:»)
Dim x As Integer = Integer.Parse(Console.ReadLine())
Console.WriteLine(«Enter y value:»)
Dim y As Integer = Integer.Parse(Console.ReadLine())
Console.WriteLine(x / y)
Catch ex As FormatException
Console.WriteLine(«Input string was not in a correct format.»)
Catch ex As InvalidOperationException
Console.WriteLine(«Not a valid numbers to perform operation»)
Catch ex As DivideByZeroException
Console.WriteLine(«Cannot Divide By Zero»)
End Try
Console.ReadLine()
End Sub
End Module
If you observe the above example, we defined multiple Catch blocks to handle different exception types so that we can easily get know what exact error it is and we can fix it easily.
When we execute the above example, we will get the result as shown below.
Enter x value:
10
Enter y value:
0
Cannot Divide By Zero
This is how we can use multiple Catch blocks with a single Try block to handle different types of exceptions based on our requirements.
Visual Basic Invalid Catch Blocks
In visual basic, defining a parameterless Catch block (Catch) and Catch block with an exception argument (Catch ex As Exception) are not allowed in the same Try-Catch statement because both will do the same thing.
Following is the example of defining an invalid Catch
blocks in same Try-Catch statement.
Try
‘ Code that may cause an exception
Catch
‘ Exception Handling
Catch ex As Exception
‘ Exception Handling
End Try
In case, if we use a parameterless catch block (Catch) or Catch block with an exception argument (Catch ex As Exception) with other Catch blocks, then those parameters must be last otherwise we will get a compile-time error.
Following is the invalid way of defining a multiple catch
blocks with a parameterless Catch
block in same Try-Catch statement.
Try
‘ Code that may cause an exception
Catch
‘ Exception Handling
Catch ex As FormatException
‘ Exception Handling
Catch ex As InvalidOperationException
‘ Exception Handling
End Try
The following are the few points which we need to consider while defining a multiple Catch blocks.
- Multiple Catch blocks with the same exception type are not allowed.
- Defining a parameterless catch block (Catch) and catch block with an exception argument (Catch ex As Exception) are not allowed in the same try-catch statement because both will do the same thing.
- While defining multiple catch blocks, the order of catch blocks must be always from most specific to least specific.
- A parameterless catch block (Catch) or catch block with an exception argument (Catch ex As Exception) must be the last block if we use it with other catch blocks otherwise we will get a compile-time error.
Visual Basic Nested Try-Catch Statements
In visual basic, we can define a Try-Catch statement within another Try-Catch statement based on our requirements. In nested Try-Catch statements, if there isn’t any inner Catch
block with an appropriate exception type, then the exception will flow to the outer Catch
block.
Following is the example of defining nested Try-Catch statements in visual basic.
Module Module1
Sub Main(ByVal args As String())
Try
Try
Console.WriteLine(«Enter x value:»)
Dim x As Integer = Integer.Parse(Console.ReadLine())
Console.WriteLine(«Enter y value:»)
Dim y As Integer = Integer.Parse(Console.ReadLine())
Console.WriteLine(x / y)
Catch ex As FormatException
Console.WriteLine(«Input string was not in a correct format.»)
End Try
Catch ex As Exception
Console.WriteLine(«Exception: « & ex.Message)
End Try
Console.ReadLine()
End Sub
End Module
If you observe the above example, we defined a Try-Catch statement within another Try-Catch statement. Here, if we get any exception other than FormatException in an inner Try-Catch statement, the exception will flow to outer Catch block until it finds an appropriate exception filter.
When we execute the above program, we will get the result like as shown below.
Enter x value:
10
Enter y value:
0
Exception: Attempted to divide by zero.
If you observe the above result, the inner Try-Catch statement has failed to handle the exception so the catch block in the outer Try-Catch statement has been handled the exception.
Visual Basic Try-Catch Overview
The following are the important points which we need to remember about the Try-Catch statement.
- In Try-Catch statement, the
Try
block will hold the code that may raise an exception and in theCatch
block, exception handling can be done. - The Try-Catch statement will contain a
Try
block followed by one or moreCatch
blocks to handle different exceptions. - In visual basic, whenever an exception occurred in the
Try
block, then the CLR (common language runtime) will look for the appropriateCatch
block that handles an exception. - In visual basic, we can use nested Try-Catch statements.
- In nested Try-Catch statements, if there isn’t any inner
Catch
block with an appropriate exception type, then the exception will be caught by an outerCatch
block.