Visual Basic.NET Programming January 28, 2004

37
Visual Basic.NET Programming January 28, 2004

description

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. - PowerPoint PPT Presentation

Transcript of Visual Basic.NET Programming January 28, 2004

Page 1: Visual Basic.NET Programming January 28, 2004

Visual Basic.NET Programming

January 28, 2004

Page 2: Visual Basic.NET Programming January 28, 2004

Class Agenda – January 28, 2004Homework

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

Page 3: Visual Basic.NET Programming January 28, 2004

Questions?

Page 4: Visual Basic.NET Programming January 28, 2004

Working with Numeric Data

Page 5: Visual Basic.NET Programming January 28, 2004

Checking Functions

• IsNumeric Function

• IsArray Function

• IsDate Function

• IsDBNull Function

• IsError Function

• IsNothing Function

• IsReference Function

• Object Data Type

• TypeName Function

Page 6: Visual Basic.NET Programming January 28, 2004

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.

Page 7: Visual Basic.NET Programming January 28, 2004

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.

Page 8: Visual Basic.NET Programming January 28, 2004

Checking For Numeric Values

If IsNumeric(TextBox1.Text) Then

End If

If Not IsNumeric(TextBox1.Text) Then

End If

Page 9: Visual Basic.NET Programming January 28, 2004

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

Page 10: Visual Basic.NET Programming January 28, 2004

/ 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".

Page 11: Visual Basic.NET Programming January 28, 2004

\ 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.

Page 12: Visual Basic.NET Programming January 28, 2004

Basic Type Data Conversions

• Data Conversion Functions

• Convert Class

Page 13: Visual Basic.NET Programming January 28, 2004

Type Conversion FunctionsThese 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)

Page 14: Visual Basic.NET Programming January 28, 2004

Convert Class

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

Page 15: Visual Basic.NET Programming January 28, 2004

• 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).

Page 16: Visual Basic.NET Programming January 28, 2004

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.

Page 17: Visual Basic.NET Programming January 28, 2004

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.

Page 18: Visual Basic.NET Programming January 28, 2004

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.

Page 19: Visual Basic.NET Programming January 28, 2004

Simple Calculator 1Class Exercise

Page 20: Visual Basic.NET Programming January 28, 2004

Exceptions in .NET

Page 21: Visual Basic.NET Programming January 28, 2004

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.

Page 22: Visual Basic.NET Programming January 28, 2004

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.

Page 23: Visual Basic.NET Programming January 28, 2004

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.

Page 24: Visual Basic.NET Programming January 28, 2004

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

Page 25: Visual Basic.NET Programming January 28, 2004

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 failEnd Try

• A Try block by itself is no good – it must be associated with at least one Catch or Finally block.

Page 26: Visual Basic.NET Programming January 28, 2004

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.Exceptionexception handling codeMessageBox.Show(e.Message)

End Try

Page 27: Visual Basic.NET Programming January 28, 2004

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.

Page 28: Visual Basic.NET Programming January 28, 2004

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.

Page 29: Visual Basic.NET Programming January 28, 2004

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.

Page 30: Visual Basic.NET Programming January 28, 2004

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.Exceptionexception handling code

Finally whatever code is place here

End Try

Page 31: Visual Basic.NET Programming January 28, 2004

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.

Page 32: Visual Basic.NET Programming January 28, 2004

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.DivideByZeroExceptionexception handling codeThrow

Catch e as System.Exceptionexception handling codeThrow New System.ApplicationException("Error...")

Finally whatever code is place here

End Try

Page 33: Visual Basic.NET Programming January 28, 2004

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.

Page 34: Visual Basic.NET Programming January 28, 2004

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 InvalidCastExceptionexception handling codeThrowcatch (InvalidCastException e1) Throw new InvalidCastException("My own info",

e)End Try

Page 35: Visual Basic.NET Programming January 28, 2004

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.

Page 36: Visual Basic.NET Programming January 28, 2004

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.

Page 37: Visual Basic.NET Programming January 28, 2004

Simple Calculator (Part 2)with

Exception Handling