1 / 37

Visual Basic.NET Programming January 28, 2004

Visual Basic.NET Programming January 28, 2004. Class Agenda – January 28, 2004. Homework Open Questions? Working with Numeric Data Simple Calculator Exercise Exceptions Simple Calculator with Exceptions More Controls (Timer, etc) Clock Exercise More Controls Homework – Control Tester.

rod
Download Presentation

Visual Basic.NET Programming January 28, 2004

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Visual Basic.NET ProgrammingJanuary 28, 2004

  2. Class Agenda – January 28, 2004 Homework Open Questions? Working with Numeric Data Simple Calculator Exercise Exceptions Simple Calculator with Exceptions More Controls (Timer, etc) Clock Exercise More Controls Homework – Control Tester

  3. Questions?

  4. Working with Numeric Data

  5. Checking Functions • IsNumeric Function • IsArray Function • IsDate Function • IsDBNull Function • IsError Function • IsNothing Function • IsReference Function • Object Data Type • TypeName Function

  6. IsNumeric Function If IsNumeric(TextBox1.Text) Then • Returns a Boolean value indicating whether an expression can be evaluated as a number. Public Function IsNumeric(ByVal Expression As Object) As Boolean • IsNumeric returns True if the entire Expression is recognized as a number; otherwise, it returns False. • IsNumeric returns True if the data type of Expression is Short, Integer, Long, Decimal, Single, or Short. • It also returns True if Expression is a String that can be successfully converted to a Double. It returns False if Expression is of data type Date.

  7. The Not Operator • The Not operator performs logical negation on a Boolean expression. Put simply, it yields the opposite of the expression it evaluates. If the expression evaluates to True, Not yields False; if the expression evaluates to False, Not yields True. An example is shown below: Dim x As Boolean x = Not 23 > 12 ' x equals False. x = Not 23 > 67 ' x equals True.

  8. Checking For Numeric Values If IsNumeric(TextBox1.Text) Then End If If Not IsNumeric(TextBox1.Text) Then End If

  9. Arithmetic Operators • The *, /, \, ^, Mod, +, and – binary operators are the arithmetic operators. • RegularDivisionOperatorExpression = Expression / Expression • Divide by zero  Infinity • IntegerDivisionOperatorExpression = Expression \ Expression • Divide by Zero  Throws Overflow Exception

  10. / Operator • Divides two numbers and returns a floating-point result. number1 / number2 • The result is the quotient of number1 divided by number2. • Attempting to perform division by zero returns the word "Infinity".

  11. \ Operator • Divides two numbers and returns an integer result. number1 \ number2 • The result is the integer quotient of number1 and number2, dropping the remainder. • Attempting to perform integer division by zero causes a DivideByZeroExeception to be thrown.

  12. Basic Type Data Conversions • Data Conversion Functions • Convert Class

  13. Type Conversion Functions These functions are compiled inline, meaning the conversion code is part of the code that evaluates the expression. Execution is faster because there is no call to a procedure to accomplish the conversion. Each function coerces an expression to a specific data type. CBool(expression) CByte(expression) CChar(expression) CDate(expression) CDbl(expression)CDec(expression) CInt(expression)CLng(expression)CObj(expression) CShort(expression)CSng(expression)CStr(expression) expression - Any String expression or numeric expression. (See Page 25 and 26 in Text)

  14. Convert Class • Converts a base data type to another base data type. Examples: • Convert.ToDouble(expression) • Convert.ToInteger(expression) • Convert.ToDateTime(expression)

  15. A conversion method exists to convert every base type to every other base type. However, the actual conversion operation performed falls into three categories: • A conversion from a type to itself simply returns that type. No conversion is actually performed. • Any base type, other than those described on the next slide, can be converted to and from any other base type. • Conversions which throw exceptions (next slide).

  16. Convert Class - Exceptions • A conversion which cannot yield a meaningful result throws InvalidCastException. No conversion is actually performed. • An exception is thrown for conversions from Char to Boolean, Single, Double, Decimal or DateTime, and from those types to Char. • An exception is thrown for conversions from DateTime to any type except String, and from any type, except String, to DateTime.

  17. Convert Class Return Types • This class returns a type whose value is equivalent to the value of a specified type. • The supported base types are Boolean, Char, SByte, Byte, Int16, Int32, Int64, Single, Double, Decimal, DateTime and String.

  18. ToString Method (Samples) • Boolean.ToString Method • Converts the value of this instance to its equivalent string representation. • Returns "True" or "False" • Double.ToString Method • Converts the numeric value of this instance to its equivalent string representation. • Integer.ToString Method • Converts the numeric value of this instance to its equivalent string representation.

  19. Simple Calculator 1Class Exercise

  20. Exceptions in .NET

  21. Exceptions in .NET • .NET Frameworks relies heavily on exception handling. • In fact all error notification/handling by the framework is in the form of exceptions. • Returning error values by your custom code is still possible, but not encouraged. • The move from error codes to exceptions will have an impact on how your code is structured and designed. • Since exceptions are part of the framework, they are consistent across all languages.

  22. Benefits of exception handling • Cleanup code is kept in a localized spot, and we can be assured that the code will run. • This implies your logic isn’t scattered with a ton of cleanup code, nor do you have to jump to cleanup blocks. (On error goto…) • Similarly, all code to handle exceptional situations is kept in a central place. • Once this is done, you write the rest of your code as id the errors can never occur. • Examples of exceptional situations are arithmetic overflows, out-of-memory conditions, attempts to access resources after they have been closed, etc. • When exceptions do occur, their is greater availability of information that will help us locate and fix the error.

  23. Exceptions • Historically error processing has been an opt-in – you can opt to handle the error, but you ignore it by default. • Exceptions change this to the opt-out model – you can explicitly choose to ignore the exception, but you must handle it by default. • If you don’t handle it, your caller gets handed the exception, and so on up the chain. • When exception handling was added to C++, it had a reputation for being slow. Part of the reason was that a fairly large burden was placed on the compiler to make sure cleanup (destruction) code was put in place whenever an exception could be thrown.

  24. Exceptions • In .NET, since all languages are built on the runtime, the runtime implements exception handling. • Unlike error codes, exceptions are objects that represent exceptional conditions, and can carry a lot of information. • In Visual Basic.NET, the following keywords are used with exceptions. • Try • Catch • Finally • Throw • End Try

  25. The Try Block • The Try block is where you put sections of code that may potentially throw exceptions. • It also contains code that requires common cleanup or exception recovery operations. Try code which may fail End Try • A Try block by itself is no good – it must be associated with at least one Catch or Finally block.

  26. The Catch Block • A Catch block contains code to execute in response to an exception. • A Try block can have zero or more catch blocks associated with it. Try code which may fail Catch e as System.Exception exception handling code MessageBox.Show(e.Message) End Try

  27. The Catch Block • If the code in the Try block doesn’t cause an exception to be thrown, the CLR never executes any code contained within the catch blocks. • The thread skips over the Catch blocks and executes code in the Finally block (if one exists.) • Any statements following the Catch/Finally blocks are executed • The expression after the catch keyword is called an exception filter. In Visual Basic.NET the exception filter has to be an object of the type System.Exception or a derivative.

  28. The Catch Block • You can place multiple Catch blocks after a try block. • The Catch blocks are searched from top to bottom. • Important: Place the more specific exceptions at the top, in the order you would like them caught. • The Visual Basic.NET compiler does generate a compile error if more general catch blocks are placed ahead of the more specific ones.

  29. The Catch Block • If none of the Catch blocks match the exception that occurred, the CLR continues up the call stack looking for one. • If none are found after reaching the top of the call stack, an unhandled exception is reported. • Within a Catch block, after any handler code you write, you can • Rethrow the same exception. • Throw a different exception. • Just fall out of the bottom. • Code in a Finally block (if present) is always executed.

  30. The Finally Block • A Finally block contains code that is guaranteed to execute. • Typically contains cleanup code required by the actions taken in the try block. • A Finally block is associated with a try block. (i.e. no Catch block is required). Try code which may fail Catch e as System.Exception exception handling code Finally whatever code is place here End Try

  31. The System.Exception Class • This class is the base class for all exceptions. • Interesting members: • Message : a string that contains a description of the exception. • Source : the name of the application or object that caused the error • StackTrace : a string representation of the stack trace at the time the exception was thrown. • HResult : Can contain an HRESULT. Why ? • Demo by breakpoint at an exception and examine the exception.

  32. Throwing an exception • Within a catch block, we can choose to rethrow the same exception, or throw a new one. Try code which may fail Catch e as System.DivideByZeroException exception handling code Throw Catch e as System.Exception exception handling code Throw New System.ApplicationException("Error...") Finally whatever code is place here End Try

  33. Guidelines for exception handling • Catch the most specific exception possible • Otherwise, you may end up handling exceptions you did not intend to. • Catch the exception only if you are absolutely sure how to handle it. • Order your exception blocks carefully. Remember, Catch blocks are executed sequentially. • Finally blocks are a good place to put cleanup code. Try not to put code that may throw exceptions in the finally block. (If it does, the application will not crash, the exception will just be passed up the call chain.) • Return values still have their place – do not use exceptions to return ‘normal’ error conditions.

  34. Wrapping an exception • A lot of times, you just want to add more descriptive information to the exception you are handling. In this case, you can wrap the exception that was just caught. InnerException will contain the original exception. Try code which may fail Catch e as InvalidCastException exception handling code Throw catch (InvalidCastException e1) Throw new InvalidCastException("My own info", e) End Try

  35. A common mistake • Folks commonly put this catch block in their code: Catch e as Exception exception handling code • Understand what this does ! – this assumes you know how to handle every kind of exception.

  36. Another common mistake • In one of the earlier slides, we did this: Catch e As InvalidCastException Throw New Exception("My own info", e) • This is generally a bad idea since we caught a more specific exception and replaced it with one that has less information.

  37. Simple Calculator (Part 2)withException Handling

More Related