Although every precaution has been taken in the preparation of this book, the information Exam Ref 70 Exam Ref Developing Microsoft Azure. This book expresses the author's views and opinions. The information contained in this book is provided without any express, statutory, or. Prepare for Microsoft Exam , and demonstrate your real-world mastery of skills Book ; eBook

Author:DAMARIS TERAULT
Language:English, Spanish, French
Country:Hungary
Genre:Biography
Pages:117
Published (Last):09.05.2016
ISBN:724-8-32522-528-3
Distribution:Free* [*Registration Required]
Uploaded by: EDWARDO

54519 downloads 130590 Views 25.63MB ePub Size Report


Exam 70 483 Ebook

Prepare for Microsoft Exam —and help demonstrate your real-world mastery of programming in C#. Designed for experienced software developers ready. Prepare for Microsoft Exam –and help demonstrate your real-world mastery of programming in C#. Designed for experienced software developers ready. Contribute to harryi3t/PDFs development by creating an account on GitHub.

Her exclamation was instantly followed by much polishing but Mrs. Maxley Neither, sir but I wants my own, and Exam Paper I wool have it too so count out M Tests on this here counter, or I ll cry the town Dump round that there door. If he succeed Book in this, that may go in mitigation of damages, though it cannot affect the verdict. She Microsoft MCSD, Easily To Pass Preparation Materials shared her hymn book with him, too, and sang her Maker s praise modestly and soberly, but earnestly, and quite undisturbed by her lover s presence. Thus the great banker stood, a colossus of wealth and stability to the eye, though ready to crumble at a touch Demo and indeed self doomed, for bankruptcy was now his game. Instantly he made a rush, and so did a wooden legged sailor but he got first to the broom, and began M Exam Engines to sweep while others picked up his countryman, who proved dead as a herring and he succeeded to his broom, and it made money by the Exchange, though he never could. And lo one day when he was cleaned out, and desperate, and hovering with the other ghosts of little capitalists about the tomb of their money, he saw his countryman fall flat, and the broom fly out of his hand. The plate cleared, and washed down with a tumbler of port, Maxley resumed, and [] Updated Daily Microsoft MCSD Cert informed the doctor that the mouse was at this moment in his garden eating his bulbs. Wincing under each heavy blow, he crept doggedly, patiently on towards that one visible hope. This was a rare opportunity, and the Robin and Certification Garrett put their heads together accordingly. Let me comfort him let me tell him you will live for his sake and mine.

One scenario where this is required is to preserve the ordering of your query. Implement multithreading and asynchronous processing Chapter 1 23 www. WriteLine e ; In contrast to foreach, ForAll does not need all results before it starts executing.

In this example, ForAll does, however, remove any sort order that is specified. Of course, it can happen that some of the operations in your parallel query throw an exception. This exception exposes a list of all exceptions that have happened during parallel execution. Listing shows how you can handle this. You can inspect those exceptions by looping through the InnerExceptions property.

Using concurrent collections When working in a multithreaded environment, you need to make sure that you are not ma- nipulating shared data at the same time without synchronizing access. These collections are thread-safe, which means that they internally use synchronization to make sure that they can be accessed by multiple threads at the same time. Those collections are the following: Removing an item from the col- lection can be blocked until data becomes available. Adding data is fast, but you can set a maximum upper limit.

If that limit is reached, adding an item blocks the calling thread until there is room. BlockingCollection is in reality a wrapper around other collection types. A regular collection blows up when being used in a multithreaded scenario because an item might be removed by one thread while the other thread is trying to read it.

Listing shows an example of using a BlockingCollection. One Task listens for new items being added to the collection. It blocks if there are no items available. The other Task adds items to the collection. Implement multithreading and asynchronous processing Chapter 1 25 www. WriteLine col. Until that, every string entered is added by the write Task and removed by the read Task.

You can use the CompleteAdding method to signal to the BlockingCollection that no more items will be added. You can even remove the while true statements from Listing By using the GetCon- sumingEnumerable method, you get an IEnumerable that blocks until it finds a new item. That way, you can use a foreach with your BlockingCollection to enumerate it see Listing ConcurrentBag A ConcurrentBag is just a bag of items.

It enables duplicates and it has no particular order.

Exam Ref Programming in C# (MCSD) by Wouter de Kort (ebook)

Listing shows how to work with the ConcurrentBag. Add 42 ; bag. It could be that another thread removes the item before you can access it. Listing shows this in practice. Sleep ; bag. Implement multithreading and asynchronous processing Chapter 1 27 www. A queue is a first in, first out FIFO collection. ConcurrentStack has two important methods: Push and TryPop. Push is used to add an item to the stack; TryPop tries to get an item off the stack.

You can never be sure whether there are items on the stack because multiple threads might be accessing your collection at the same time. When you enumerate the collection, a snapshot is taken. Listing shows how these methods work. It also has a TryPeek method and it implements IEnumerable by making a snapshot of the data. Listing shows how to use a ConcurrentQueue. You can use meth- ods to add and remove items, and to update items in place if they exist.

Listing shows the methods that you can use on a ConcurrentDictionary. An atomic operation means that it will be started and finished as a single step without other threads interfering. TryUpdate checks to see whether the current value is equal to the existing value before updating it.

You need to build a new application, and you look into multithreading capabili- ties. Your application consists of a client application that communicates with a web server. Explain how multithreading can help with your client application.

Does using multithreading with the TPL offer the same advantages for your server application? Implement multithreading and asynchronous processing Chapter 1 29 www. Other- wise, you can use the ThreadPool to queue work and let the runtime handle things.

Tasks are the recommend- ed way to create multithreaded code. Objective review Answer the following questions to test your knowledge of the information in this objective.

You have a lot of items that need to be processed. For each item, you need to perform a complex calculation. Which technique should you use? You create a Task for each item and then wait until all tasks are finished.

You use Parallel. For to process all items concurrently. You add all items to a BlockingCollection and process them on a thread created by the Thread class. Which method should you use? AsParallel B. AsSequential C. AsOrdered D. You are working on an ASP. NET application that retrieves some data from another web server and then writes the response to the database.

No, both operations depend on external factors. You need to wait before they are finished. Problems can happen when different threads access some shared data. What should happen when both try to change something at the same time? To make this work successfully, synchronizing resources is important. Synchronizing resources As you have seen, with the TPL support in. But when you build real-world applications with multithreading, you run into prob- lems when you want to access the same data from multiple threads simultaneously.

Listing shows an example of what can go wrong. Manage multithreading Chapter 1 31 www. The answer is, it depends. When you run this application, you get a different output each time.

The seemingly simple operation of incre- menting and decrementing the variable n results in both a lookup check the value of n and add or subtract 1 from n. But what if the first task reads the value and adds 1, and at the exact same time task 2 reads the value and subtracts 1? This is because the operation is not atomic. It consists of both a read and a write that happen at different moments. One feature the C language offers is the lock operator, which is some syntactic sugar that the compiler translates in a call to System.

Listing shows the use of the lock operator to fix the previous example. There is no way that one thread could change the value while the other thread is working with it. However, it also causes the threads to block while they are waiting for each other. This can give performance problems and it could even lead to a deadlock, where both threads wait on each other, causing neither to ever complete.

Listing shows an example of a deadlock. Manage multithreading Chapter 1 33 www. The first Task locks A and waits for B to become free. The main thread, however, has B locked and is waiting for A to be released.

You need to be careful to avoid deadlocks in your code. You can avoid a deadlock by mak- ing sure that locks are requested in the same order. That way, the first thread can finish its work, after which the second thread can continue.

The lock code is translated by the compiler into something that looks like Listing The compiler takes care of tricky edge cases that can happen. A public object could be used by other threads to acquire a lock without your code knowing.

It should also be a reference type because a value type would get boxed each time you acquired a lock. In practice, this generates a completely new lock each time, losing the locking mechanism. Fortunately, the compiler helps by raising an error when you accidentally use a value type for the lock statement.

You should also avoid locking on the this variable because that variable could be used by other code to create a lock, causing deadlocks. For the same reason, you should not lock on a string. Because of string-interning the pro- cess in which the compiler creates one object for several strings that have the same content you could suddenly be asking for a lock on an object that is used in multiple places.

Volatile class The C compiler is pretty good at optimizing code.

70-483 Ebook – Free Microsoft Exams Learning Center

The compiler can even remove complete statements if it discovers that certain code would never be executed. The compiler sometimes changes the order of statements in your code. But take a look at Listing , in which a problem could happen in a multithreaded environment. It could be, however, that the compiler switches the two lines in Thread1. You can use locking to fix this, but there is also another class in the. NET Framework that you can use: This class has a special Write and Read method, and those methods disable the compiler optimizations so you can force the correct order in your code.

Using these methods in the correct order can be quite complex, so. NET offers the volatile keyword that you can apply to a field.

You would then change the declaration of your field to this: Because it disables certain compiler optimizations, it will hurt performance. The Interlocked class Referring to Listing , the essential problem was that the operations of adding and sub- tracting were not atomic.

Making operations atomic is the job of the Interlocked class that can be found in the Sys- tem. When using the Interlocked. Increment and Interlocked. Decrement, you create an atomic operation, as Listing shows. Manage multithreading Chapter 1 35 www.

No other thread will see any intermediate results. Of course, adding and subtracting is a simple operation. If you have more complex operations, you would still have to use a lock. Interlocked also supports switching values by using the Exchange method. You use this method as follows: It returns the previous value before changing it.

You can also use the CompareExchange method. This method first checks to see whether the expected value is there; if it is, it replaces it with another value. Listing shows what can go wrong when comparing and exchanging a value in a non- atomic operation. At the same time, t2 changes the value to 3 and then t1 changes it back to 2. To avoid this, you can use the following Inter- locked statement: This way, no other thread can change the value between comparing and exchang- ing it.

NET Framework offers a special class that can help you in canceling these tasks: You pass a CancellationToken to a Task, which then periodically monitors the token to see whether cancellation is requested. Listing shows how you can use a CancellationToken to end a task.

Manage multithreading Chapter 1 37 www. ReadLine ; cancellationTokenSource. Cancel ; Console. The CancellationTokenSource is used to signal that the Task should cancel itself. In this case, the operation will just end when cancellation is requested.

If you want to signal to outside users that your task has been canceled, you can do this by throwing an OperationCanceledException. WriteLine e. Listing shows what such a continuation task would look like. OnlyOnCanceled ; If you want to cancel a Task after a certain amount of time, you can use an overload of Task. WaitAny that takes a timeout. Manage multithreading Chapter 1 39 www.

You are experiencing deadlocks in your code. How can you orchestrate your locking code to avoid deadlocks? How can the Interlocked class help you? You want to synchronize access by using a lock statement. On which member do you lock?

You need to implement cancellation for a long running task. Which object do you pass to the task? CancellationTokenSource B. CancellationToken C.

Boolean isCancelled variable D. Volatile 3. You are implementing a state machine in a multithreaded class. You need to check what the current state is and change it to the new one on each step. Which method do you use?

Write ref currentState B. Exchange ref currentState, newState D. Decrement ref newState Objective 1. Implement program flow One important aspect of managing the flow of your program is making decisions in your ap- plication, including checking to see whether the user has entered the correct password, mak- ing sure that a certain value is within range, or one of the myriad other possibilities. C offers a couple of statements that can be used when you need to make a decision.

Next to making decisions, another common task is working with collections. C has lan- guage features that help you work with collections by allowing you to iterate over collections and access individual items. Working with Boolean expressions When working with flow control statements, you will automatically work with Boolean expres- sions.

A Boolean expression should always produce true or false as the end result, but in doing so they can be quite complex by using different operators. Implement program flow Chapter 1 41 www. You use this one to test that two values are equal to each other. Listing shows some examples. These operators use both a left and a right operand, meaning the left and right part of the expression.

The OR operator returns true when one of both operands is true. If both are false, it returns false. If both are true, it will return true. This is called short-circuiting. The AND operator can be used when both parts of an expression need to be true. If either one of the operands is false, the whole expression evaluates to false. Listing uses the AND operator to check to see whether a value is within a certain range.

Just as with the OR operator, the runtime applies short-circuiting. Next to being a performance optimization, you can also use it to your advantage when working with null values. Listing for example uses the AND operator to check if the input argument is not null and to execute a method on it. Table gives the possibilities for the XOR operator.

Implement program flow Chapter 1 43 www. Listing shows how to use the XOR operator. You can use the following statements: Using these constructs, you can create flexible applications that enable you to execute dif- ferent behavior depending on the circumstances. The if statement The most widely used flow control statement is the if statement. The if statement enables you to execute a piece of code depending on a specific condition.

The general syntax for the if statement is this: List- ing shows an example of using if. If b would be false, the Console. WriteLine statement would not be executed. Of course, passing a hard-coded value to the if statement is not very useful. Normally, you would use the if statement with a more dynamic value that can change during the execution of the application. A block uses curly-braces to denote its start and end: You can, however, also use a code block after the if statement.

All code in the block is executed based on the result of the if statement. You can see an example of this in Listing This means that you can declare variables inside a block, and use them within the block but not outside the block. Listing shows the scoping differ- ences. Variable b is declared outside the block and can be accessed both in the outer block and in the if statement. Variable r, however, can be accessed only in the if statement.

Implement program flow Chapter 1 45 www. You can do this by using an else block. The general syntax looks like this: Under normal circumstances, you should worry more about readability than about the num- ber of lines you produce. The null-coalescing operator The?? You can use it to provide a default value for nullable value types or for reference types. Listing shows an example of using the operator. You can also nest the null-coalescing operator, as Listing shows.

The conditional operator The conditional operator?: If the expression is true, the first value is returned; otherwise, the second.

Listing shows an example of how the operator can be used to simplify some code. In this case, the if statement can be replaced with the conditional operator. Implement program flow Chapter 1 47 www. Take the example of List- ing A switch state- ment checks the value of its argument and then looks for a matching label.

Listing shows the code from Listing as a switch statement. In Listing , all the vowels belong to the same switch-section. If you want, you can also add a default label that is used when none of the other labels matches.

The end point of a switch statement should not be reachable. You need to have a state- ment such as break or return that explicitly exits the switch statement, or you need to throw an exception. This makes it possible for switch sections to appear in any order without affecting behavior. Instead of implicitly falling through to another label, you can use the goto statement see Listing Implement program flow Chapter 1 49 www. Collections are widely used in C , and the language offers constructs that you can use with them: Listing shows an example in which you loop through all items in an array.

When the condition equals false, the loop is exited. None of these parts is required. You can also use multiple statements in each part of your for loop see List- ing For example, you can change Listing to increment index with 2 to only display the odd numbers, as Listing shows.

You can do this by using the break or return statement when you want to completely exit the method. Listing shows an example of the break statement. Listing shows an example in which the number 4 is skipped in the loop. Implement program flow Chapter 1 51 www. A for loop is nothing more than a convenient way to write a while loop that does the checking and incrementing of the counter.

Notice the extra parenthesis to restrict the scope of the loop variable. You should use a for loop when you know the number of iterations in advance. This is different when using a do-while loop. A do-while loop executes at least once, even if the expression is false. Listing shows an example of using a do-while loop. The foreach loop keeps track of where it is in the collection and protects you against iterating past the end of the collection.

Listing shows an example of how to use the foreach loop. You can use the continue and break statements to influence the way the foreach loop works. The loop variable cannot be modified. Listing shows these differences. When the compiler encounters a foreach statement, it generates some code on your behalf; foreach is syntactic sugar that lets you write some code in a nice way.

Implement program flow Chapter 1 53 www. MoveNext is called. Jump statements Another type of statement that can be used to influence program flow is a jump statement. You have already looked at two of those statements: A jump statement unconditionally transfers control to another location in your code.

Another jump statement that can be used to change the flow of a program is goto. The goto statement moves control to a statement that is marked by a label. Listing shows an example of using goto and a label. The compiler also makes sure that any finally blocks that intervene are executed. If possible, however, you should try to avoid them. By refactoring your code, you can remove them most of the time and this will improve the readability of your code.

The goto statement is even worse. It is considered a bad practice. Although C restricts the way the goto operator behaves, as a guideline, you should try to avoid using goto. The application is used by hotels to keep track of reservations and guests coming and leaving.

You are going through the old code base to determine whether there is code that can be easily reused. You notice a couple of things: What is the disadvantage of using goto? How can you avoid using the goto statement?

Which statement can you use to improve the long if statements? What are the differences between the for and foreach statement? When should you use which? Implement program flow Chapter 1 55 www. You need to iterate over a collection in which you know the number of items. You need to remove certain items from the collection. Which statement do you use?

You have a lot of checks in your application for null values. If a value is not null, you want to call a method on it. You want to simplify your code. Which technique do you use? Conditional operator C. Null-coalescing operator D. The short-circuiting behavior of the and operator 3. You are processing some data from over the network. You use a HasNext and Read method to retrieve the data.

You need to run some code on each item. What do you use? Create and implement events and callbacks An event can be used to provide notifications. You can subscribe to an event if you are inter- ested in those notifications. You can also create your own events and raise them to provide notifications when something interesting happens.

NET Framework offers built-in types that you can use to create events. By using delegates, lambda expressions, and anonymous methods, you can create and use events in a comfortable way.

Understanding delegates In C , delegates form the basic building blocks for events. A delegate is a type that defines a method signature. In C you can instantiate a delegate and let it point to another method. You can invoke the method through the delegate. Listing shows an example of declaring a delegate and calling a method through it.

Delegates can be nested in other types and they can then be used as a nested type. Create and implement events and callbacks Chapter 1 57 www. An instantiated delegate is an object; you can pass it around and give it as an argument to other methods.

Another feature of delegates is that you can combine them together. This is called multi- casting. All this is possible because delegates inherit from the System. MulticastDelegate class that in turn inherits from System. Because of this, you can use the members that are defined in those base classes on your delegates. For example, to find out how many methods a multicast delegate is going to call, you can use the following code: GetLength 0 ; When you assign a method to a delegate, the method signature does not have to match the delegate exactly.

This is called covariance and contravariance. Covariance makes it pos- sible that a method has a return type that is more derived than that defined in the delegate. Contravariance permits a method that has parameter types that are less derived than those in the delegate type. Listing shows an example of covariance. An example of contravariance can be seen in Listing Because of contravariance, you can call the delegate and pass an instance of StreamWriter to the DoSomething method.

Using lambda expressions Sometimes the whole signature of a method can be more code than the body of a method. There are also situations in which you need to create an entire method only to use it in a delegate. For these cases, Microsoft added some new features to C. Lambda expressions are the preferred way to go when writing new code. Listing shows how you would write the example in Listing with newer lambda syntax. Create and implement events and callbacks Chapter 1 59 www.

Because of this, lambda functions are called anonymous functions. The compiler infers this automatically from your lambda. And in the case of Listing , the types of the parameters x and y are also not specified explicitly. As you can see, the syntax for writing a lambda can be compact.

If a lambda has only one parameter, you can even remove the parentheses around the parameter. You can create lambdas that span multiple statements. You can do this by adding curly braces around the statements that form the lambda as Listing shows.

Because of this, the. NET Framework has a couple of built-in delegate types that you can use when declaring del- egates. For the Calculate examples, you have used the following delegate: All those types inherit from System. MulticastDel- egate so you can add multiple methods to the invocation list.

Exam Ref 70-483 Programming in C#, 2nd Edition

Action types. Listing shows an example of using the Action type. Normally, when control leaves the scope of a variable, the variable is no longer valid. But what if a delegate refers to a local variable and is then returned to the calling method? Now, the delegate has a longer life than the variable. To fix this, the compiler generates code that makes the life of the captured variable at least as long as the longest-living delegate.

This is called a closure. Using events A popular design pattern a reusable solution for a recurring problem in application devel- opment is that of publish-subscribe. You can subscribe to an event and then you are notified when the publisher of the event raises a new event.

This is used to establish loose coupling between components in an application. Delegates form the basis for the event system in C. Listing shows how a class can expose a public delegate and raise it.

The Pub class is completely unaware of any subscribers. It just raises the event. If there would be no subscribers to an event, the OnChange property would be null.

This is why the Raise method checks to see whether OnChange is not null. Although this system works, there are a couple of weaknesses. Create and implement events and callbacks Chapter 1 61 www. However, nothing prevents outside users of the class from raising the event. By just calling p. OnChange every user of the class can raise the event to all subscribers.

To overcome these weaknesses, the C language uses the special event keyword. Listing shows a modified example of the Pub class that uses the event syntax. First, you are no lon- ger using a public property but a public field. Normally, this would be a step back. However, with the event syntax, the compiler protects your field from unwanted access. Another change is that no outside users can raise your event.

Listing also uses some special syntax to initialize the event to an empty delegate. This way, you can remove the null check around raising the event because you can be certain that the event is never null. As long as none of your other class members sets the event to null, you can safely assume that it will always have a value.

There is, however, one change you still have to make to follow the coding conventions in the. EventHandler is declared as the following delegate: The sender is by conven- tion the object that raised the event or null if it comes from a static method. When raising this event, you are required to pass an instance of MyArgs.

Subscribers to the event can access the arguments and use it. Although the event implementation uses a public field, you can still customize addition and removal of subscribers. This is called a custom event accessor. Listing shows an exam- ple of creating a custom event accessor for an event. Create and implement events and callbacks Chapter 1 63 www. Instead of get and set you use add and remove. Man- age multithreading," earlier in this chapter. If you use the regular event syntax, the compiler generates the accessor for you.

This makes it clear that events are not delegates; instead they are a convenient wrapper around delegates. Delegates are executed in a sequential order.

Also read: MADDEN 15 EBOOK

One thing that is a direct result of the sequential order is how to handle exceptions. Listing shows an example in which one of the event subscribers throws an error. If this is not the behavior you want, you need to manually raise the events and handle any exceptions that occur. You can do this by using the GetInvocationList method that is declared on the System. Delegate base class. Listing shows an example of retrieving the subscribers and enumerating them manually.

Create and implement events and callbacks Chapter 1 65 www. WriteLine ex. Implement exception handling" later in this chapter. You are working on a desktop application that consists of multiple forms. Those forms show different views of the same data and they should update in real time. Your application is extensible, and third parties can add plug-ins that contain their own views of the data.

Should you use delegates or events in this system? How can this help you? Users of events can only remove and add methods the invocation list. Create and implement events and callbacks Chapter 1 67 www.

You have a private method in your class and you want to make invocation of the method possible by certain callers. What do you do? Make the method public. Use an event so outside users can be notified when the method is executed. Use a method that returns a delegate to authorized callers.

Declare the private method as a lambda. You have declared an event on your class, and you want outside users of your class to raise this event. Make the event public.

Add a public method to your class that raises the event. Use a public delegate instead of an event. Use a custom event accessor to give access to outside users. You are using a multicast delegate with multiple subscribers.

You want to make sure that all subscribers are notified, even if an exception is thrown. Manually raise the events by using GetInvocationList. This is the default behavior. Let subscribers return true or false instead of throwing an exception. Implement exception handling When you build your applications, sometimes errors occur. Maybe you want to write a file to disk, and the disk is full. You try to connect to a database, but the database server is unavail- able or another unexpected condition exists.

Instead of working with error codes, the. NET Framework uses exceptions to signal errors. You can also use these exceptions to signal errors that happen in your own applications and you can even create custom exception types to signal specific errors. Handling exceptions When an error occurs somewhere in an application, an exception is raised. Exceptions have a couple of advantages compared with error codes. An exception is an object in itself that con- tains data about the error that happened.

It not only has a user-friendly message but it also contains the location in which the error happened and it can even store extra data, such as an address to a page that offers some help. If an exception goes unhandled, it will cause the current process to terminate.

Listing shows an example of an application that throws an error and shuts down. Parse method throws an exception of type FormatException when the string is not a valid number.

Throwing an exception halts the execution of your application. Instead of continuing to the following line, the runtime starts searching for a location in which you handle the exception. If such a location cannot be found, the exception is unhandled and will terminate the application. Listing shows an example of catching the FormatException. Implement exception handling Chapter 1 69 www. Following the try statement, you can add several different catch blocks.

How much code you put inside each try block depends on the situation. If you have multiple statements that can throw the same exceptions that need to be handled differently, they should be in different try blocks.

A catch block can specify the type of the exception it wants to catch. Because all exceptions in the. NET Framework inherit from System. Exception, you can catch every possible exception by catching this base type. You can catch more specific exception types by adding extra catch blocks. The catch blocks should be specified as most-specific to least-specific because this is the order in which the runtime will examine them. When an exception is thrown, the first match- ing catch block will be executed.

If no matching catch block can be found, the exception will fall through. Listing shows an example of catching two different exception types. If the string is not a num- ber, a FormatException will be thrown. By using different catch blocks, you can handle those exceptions each in their own way. Exception is automatically wrapped in a System. Since this exception inherits from System. Exception, there is no need for the empty catch block anymore. This could mean that you need to revert changes that your try block made before the exception was thrown.

Another important feature of exception handling is the ability to specify that certain code should always run in case of an exception. The finally block will execute whether an exception happens or not.

Listing shows an example of a finally block. Implement exception handling Chapter 1 71 www. For example, when the try block goes into an infinite loop, it will never exit the try block and never enter the finally block. And in situations such as a power outage, no other code will run.

The whole operating system will just terminate. There is one other situation that you can use to prevent a finally block from running. Preventing the finally block from running can be achieved by using Environment.

This method has two different overloads, one that only takes a string and another one that also takes an exception. When this method is called, the message and optionally the excep- tion are written to the Windows application event log, and the application is terminated. Listing shows how you can use this method. When you run this application without a debugger attached, a message is written to the event log.

Instead the application shuts down immediately. Table lists the properties of the base System. Exception class. Exception properties Name Description StackTrace A string that describes all the methods that are currently in execution.

This gives you a way of tracking which method threw the exception and how that method was reached. InnerException When a new exception is thrown because another exception happened, the two are linked together with the InnerException property.

Message A hopefully human friendly message that describes the exception. HResult A bit value that describes the severity of an error, the area in which the excep- tion happened and a unique number for the exception This value is used only when crossing managed and native boundaries. Source The name of the application that caused the error. If the Source is not explicitly set, the name of the assembly is used. TargetSite Contains the name of the method that caused the exception. If this data is not available, the property will be null.

This data can be read by other catch blocks and can be used to control the processing of the exception. Implement exception handling Chapter 1 73 www. This way, you effectively create a variable that will hold the exception for you so you can inspect its properties. When this happens, control immediately leaves the finally block and moves to the next outer try block, if any.

You should only catch an exception when you can resolve the issue or when you want to log the error. This way, you could accidentally swallow an important exception without even knowing that it happened.

Logging should also be done somewhere higher up in your application. That way, you can avoid logging duplicate errors at multiple layers in your application. Throwing exceptions When you want to throw an error, you first need to create a new instance of an exception. You can then use the special throw keyword to throw the exception.

After this, the runtime will start looking for catch and finally blocks. Listing shows how you can throw an exception. Each time you throw an exception, you should create a new one, especially when working in a multithreaded environment, the stack trace of your exception can be changed by another thread.

When catching an exception, you can choose to rethrow the exception. You have three ways of doing this: The first option rethrows the exception without modifying the call stack. Listing shows an example of using this mechanism. Implement exception handling Chapter 1 75 www. Using the third option can be useful when you want to raise another exception to the caller of your code. Say, for example, that you are working on an order application. When a user places an or- der, you immediately put this order in a message queue so another application can process it.

When an internal error happens in the message queue, an exception of type Message- QueueException is raised. Instead, you can throw another exception, something like a custom OrderProcessingExcep- tion, and set the InnerException to the original exception.

In your OrderProcessingException you can put extra information for the user of your code to place the error in context and help them solve it. The original exception is preserved, including the stack trace, and a new exception with extra information is added. Throw a new exception that points to the original one when you want to add extra infor- mation; otherwise, use the throw keyword without an identifier to preserve the original exception details.

You can use the Exception- DispatchInfo. Throw method, which can be found in the System. ExceptionServices namespace. This method can be used to throw an exception and preserve the original stack trace. Do go and see her Hum The fact is, her brother is a great favourite of mine. There is a mystery a dreadful mystery may he not Sale Best Microsoft MCSD Exam Demo be as mystified, too, and perhaps Exam Paper tortured like me with doubts and suspicions They say he is pale and dejected.

The third plea was the stinger, but too long to cite verbatim it went to this tune, that the plaintiff at and before the time c. Bazalgette s was the letter of a smooth woman, who has hoarded imperishable spite. To know people s real estimate of themselves, study their language of self depreciation. Bar the fell dragon s blighting way but shun that lovely snare. Dodd sold it under the rose to a fat old dowager for whom nothing was too fine Demo and so kept up appearances.

If he does not, I shall perhaps call at his bank, and draw a cheque for fourteen thousand pounds. But a Wadham man, who was one of the ambassadors, interposed. Wycherley fenced with this question, but the remorseless Colt only kept him longer under torture, and dragged out MCSD of him that he received fifteen per cent.

These nocturnal illusions, these imaginary sights and sounds, come of brooding on a single idea, and often usher in a calamity one trembles to think of. The servants were next told, and received warning the one Microsoft we had the poorest opinion of, she is such a flirt, cried, and begged mamma to let her share our fallen fortunes, and said she could cook a little and would do her best. She contrived this with diabolical, no, angelical cunning, to save the old man from ridicule, and to do his Exam Dumps soul much good.

When a man has a deep anxiety, some human midge or mosquito buzzes at him. To see a dozen honest gentlemen wishing to do justice, Answers able to do justice by one manly stroke of the pen, yet forego their vantage ground, and descend to coax Demo an able rogue to do their duty and undo his own interest and rascality To Microsoft see a strong cause turned into a weak one by the timidity of champions clad by law in complete steel and a rotten cause, against which Law and Power, as well as Truth, Justice, and Common Sense, had now declared, turned into Exam Paper a strong one by the pluck and cunning of his one unarmed enemy The ancients feigned that the ingenious gods tortured Tantalus in hell by ever present thirst, and water flowing to just Microsoft the outside of his lips.

How good it was of her, he thought, to come day after day and feed a poor little fellow like him, body and soul.

Related articles:


Copyright © 2019 terney.info.
DMCA |Contact Us