TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to VBNET

VB.NET Exception Handling: Try, Catch and Finally

Understand exceptions. Use the Try, Catch and Finally constructs.
Exception. Bad things happen. In VB.NET programs, many things can go wrong. Sometimes these errors are our fault. Other times, they are unavoidable, inescapable yet potentially harmful. With Exceptions, we isolate and handle these errors.
Example. To begin, we write a small program that tries to divide by zero. We use Integer.Parse here to avoid a compile-time-error. The runtime itself throws the DivideByZeroException. In the Catch block, we display the exception Message.

Note: The Try block is required to use a Catch block. If we use no try nor catch, the exception is still thrown.

But: If we do not use a Catch statement, and none is found in calling methods, the exception will cause the program to terminate.

VB.NET program that uses Try, Catch Module Module1 Sub Main() Try ' Try to divide by zero. Dim value As Integer = 1 / Integer.Parse("0") ' This statement is sadly not reached. Console.WriteLine("Hi") Catch ex As Exception ' Display the message. Console.WriteLine(ex.Message) End Try End Sub End Module Output Arithmetic operation resulted in an overflow.
Throw. An Exception can be triggered directly by the .NET Framework. But often code will use an explicit Throw-statement. We can specify a message in the Exception constructor—a descriptive string (not "mega-error") is advisable.
VB.NET program that uses Throw statement Module Module1 Sub Main() Try ' Throw a serious exception. Throw New Exception("Mega-error") Catch ex As Exception ' Display the exception's message. Console.WriteLine(ex.Message) End Try End Sub End Module Output Mega-error
NullReferenceException. Strings are prevalent in VB.NET programs. They are a reference type, which means they can be Nothing (null). If you call a method on a Nothing string, you will get a NullReferenceException. You could catch this, with the Catch statement.

However: It is more efficient to simply check for Nothing, with the "Not Nothing" construct. More information on Nothing is available.

NothingIf Then
Code that causes NullReferenceException: VB.NET Dim value As String = Nothing Console.WriteLine(value.Length) Exception text: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. Code that avoids exception: VB.NET Dim value As String = Nothing If Not value Is Nothing Then Console.WriteLine(value.Length) End If
Performance. Performance is a critical consideration when using exceptions in VB.NET programs. The only fast exception is one that never occurs. An exception that is thrown is slower than most other CPU-based operations.

So: One strategy is to reserve exceptions for "exceptional" conditions, not normal ones. If a value may be zero, check it before dividing.

However: If an important file is missing from your program's setup, an exception is warranted. This is an exceptional condition.

Finally. Try try-catch construct optionally has a third part. The finally-statement can be used after the other parts. It is always run, except when the program terminates for external reasons. It is run after exceptions are thrown.

And: Finally statements are run after catch blocks are reached. It can be used to execute cleanup code.

Tip: The Using-statement, which ensures cleanup of resources, is implemented with the Finally statement. It is a form of syntactic sugar.

Here: In this example, all 5 Console.WriteLine calls are reached. An exception is triggered in the Try-block.

Then: The Catch-block's statements are executed. And finally, the Finally statement is reached.

VB.NET program that uses Finally Module Module1 Sub Main() Console.WriteLine(0) Try ' Reached. Console.WriteLine(1) ' An exception is thrown. Dim s As String = Nothing s = s.ToUpper() Catch ex As Exception ' Reached. Console.WriteLine(2) Finally ' Reached. Console.WriteLine(3) End Try Console.WriteLine(4) End Sub End Module Output 0 1 [in Try] 2 [in Catch] 3 [in Finally] 4
Summary. Programming is complex. With computers, many things can go wrong—some problems are inevitable. Exception handling isolates error checks in our code. This leads to programs that are still fast, but also simpler to read and maintain.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf