70-483 pdf download
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. 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. 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. This way, you effectively create a variable that will hold the exception for you so you can inspect its properties. Message ; Console.
StackTrace ; Console. HelpLink ; Console. InnerException ; Console. TargetSite ; Console. String, System. 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.
The first option rethrows the exception without modifying the call stack. Listing shows an example of using this mechanism. 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.
You can use this method even outside of a catch block, as shown in Listing ReadLine ; int. Throw is used: End of stack trace from previous location where exception was thrown This feature can be used when you want to catch an exception in one thread and throw it on another thread. By using the ExceptionDispatchInfo class, you can move the exception data between threads and throw it. You know that when users start entering information into your application, they will make mistakes.
Maybe they enter a number in the wrong format or forget to enter a required field. Raising an excep- tion for these kinds of expected situations is not recommended.
Exception handling changes the normal expected flow of your program. This makes it harder to read and maintain code that uses exceptions, especially when they are used in normal situations. Using exceptions also incurs a slight performance hit. But for regular program flow, it should be avoided. Instead you should have proper validation and not rely solely on exceptions.
Because developers will be familiar with these exceptions, they should be used whenever possible. Some exceptions are thrown only by the runtime.
Table lists those exceptions. ArrayTypeMismatchException Thrown when you want to store an incompatible element inside an array. DivideByZeroException Thrown when you try to divide a value by zero. InvalidCastException Thrown when you try to cast an element to an incompat- ible type.
OverflowException Thrown when an arithmetic operation overflows in a checked context. Table shows popular ex- ceptions in the. NET Framework that you can use. ArgumentException Throw this exception when an argument to your method is invalid. ArgumentOutOfRangeException A specialized form of ArgumentException that you can throw when an argument is outside the allowable range of values.
FormatException Throw this exception when an argument does not have a valid format. NotImplementedException This exception is often used in generated code where a method has not been implemented yet. ObjectDisposedException Throw when a user of your class tries to access methods when Dispose has already been called. You should avoid directly using the Exception base class both when catching and throwing exceptions. Instead you should try to use the most specific exception available.
But there are situations in which you want to use a custom exception. This is especially useful when developers working with your code are aware of those exceptions and can handle them in a more specific way than the framework exceptions.
A custom exception should inherit from System. You need to provide at least a parameterless constructor. Listing shows an example of a custom exception. When creating your custom exception, you can decide which extra data you want to store.
Exposing this data through properties can help users of your exception inspect what has gone wrong. You should never inherit from System. The original idea was that all C runtime exceptions should inherit from System. Exception and all custom exceptions from System. However, because the. You are designing a new application and you want to implement a proper error- handling strategy.
You are also having a discussion about when to create a custom exception and when to use the built-in. NET Framework exceptions. Explain to your colleague the advantages of Exceptions compared to error codes. When should you create a custom exception? NET Framework, you should use exceptions to report errors instead of error codes. Otherwise, you should use the standard. NET Frame- work exceptions.
You are checking the arguments of your method for illegal null values. If you encounter a null value, which exception do you throw? Your code catches an IOException when a file cannot be accessed. You want to give more information to the caller of your code. Change the message of the exception and rethrow the exception. Throw a new exception with more detailed info. Use throw to rethrow the exception and save the call stack. You are creating a custom exception called LogonFailedException.
Which constructors should you at least add? Choose all that apply. LogonFailed B. LogonFailed string message C. LogonFailed string message, Exception innerException D. You can do this by using the lock statement. Lambda expressions are a shorthand syntax for creating anonymous methods inline. You can throw exceptions, catch them, and run code in a finally block. Multithreading can improve the responsiveness in a client application. The UI thread can process requests from the user while background threads execute other operations.
A CPU-bound operation needs a thread to execute. In a client application, it can make sense to execute a CPU-bound operation on another thread to improve responsive- ness. Using multithreading in a server environment can help you distribute operations over multiple CPUs.
This way, you can improve performance. Correct answer: B A. Incorrect: Manually creating and managing tasks is not necessary. The Parallel class takes care of this and uses the optimal configuration options.
Correct: Parallel. For is ideal for executing parallel operations on a large set of items that have to do a lot of work. Instead it waits until the current task has finished and then continues executing the code. Incorrect: The BlockingCollection can be used to share data between multiple threads. The Parallel class is designed for this scenario and should be used. Correct answer: A A. Correct: AsParallel makes a sequential query parallel if the runtime thinks this will improve performance.
Incorrect: AsSequential is used to make a parallel query sequential again. Incorrect: AsOrdered is used to make sure that the results of a parallel query are returned in order. Incorrect: WithDegreeOfParallelism is used to specify how many threads the par- allel query should use. Answers Chapter 1 83 www. Correct answer: C A. That way your thread can do some other work while waiting for the external responses to come back.
In the meantime, the thread can do other work. Instead, your thread can process other work while the operating system monitors the status of the request. When the request finishes, a thread is used to process the response. With a CPU-bound operation, your thread waits for the operation to finish on another thread. As soon as you start locking dependent objects in different orders, you start getting deadlocks.
The Interlocked class can help you to execute small, atomic operations without the need for locking. When you use locking a lot for these kind of operations, you can replace them with the Interlocked statement. Correct answer: D A. Incorrect: You should never lock on this. Another part of your code may already be using your object to execute a lock. With string-interning, one object can be used for multiple strings, so you would be locking on an object that is also in use in other locations.
Incorrect: Locking on a value type will generate a compile error. The value type will be boxed each time you lock on it, resulting in a unique lock each time. Correct: A private lock of type object is the best choice. The token should be passed to the task, and the CancellationTokenSource can then be used to request cancellation on the token.
A CancellationToken offers more flexibility and should be used. Incorrect: Volatile. Write is used to signal to the compiler that writing the value to a field should happen at that exact location.
Correct: CompareExchange will see whether the current state is correct and it will then change it to the new state in one atomic operation. Incorrect: Decrement is used to subtract one off the value in an atomic operation. Using the goto statement makes your code much harder to read because the appli- cation flow jumps around. You can then replace goto with while or do-while. The switch statement can be used to improve long if statements.
The for statement can be used to iterate over a collection by using an index. You can modify the collection while iterating. You need to use the index to retrieve each item. Answers Chapter 1 85 www. Incorrect: switch is used as a decision statement. Correct: With for, you can iterate over the collection while modifying it. Incorrect: goto is a jump statement that should be avoided. Incorrect: The conditional operator can be used to shorten if statements.
Correct: Short-circuiting enables you to see whether a value is null and call a member on it in one and statement. Incorrect: A for statement is most useful when iterating over a collection in which you know the number of items beforehand.
Incorrect: foreach can be used only on types that implement IEnumerable. Correct: You can use while o. When o. HasNext returns false, you automatically end the loop. Incorrect: Do-while will run the code at least once. Events are a nice layer on top of delegates that make them easier and safer to use. They can only listen to changes. The advantage of using an event system in an application like this is that you can achieve loose coupling.
Third-party plug-ins can easily subscribe to the events at runtime to be able to respond to changes without tightly coupling to the existing system. Incorrect: Making the method public gives access to all users of your class. Correct: The method can see whether the caller is authorized and then return a delegate to the private method that can be invoked at will. They can only add and remove subscribers.
Only the class itself can raise the event. Correct: The public method can be called by outside users of your class. Internally it can raise the event.
Incorrect: Using a delegate does allow it to be invoked from outside the class. However, you lose the protection that an event gives you. A public delegate can be completely modified by outside users without any restrictions. Incorrect: Canonical name CNAME records map an alias or nickname to the real or canonical name that might lie outside the current zone.
Correct: You can handle each individual error and make sure that all subscribers are called. Incorrect: By default, the invocation of subscribers stops when the first unhandled exception happens in one of the subscribers. Incorrect: Exceptions are the preferred way of dealing with errors. Returning a value from each event still requires you to invoke them manually one by one to check the return value.
Answers Chapter 1 87 www. NET Framework also offers special support for dealing with excep- tions. For example, you can use catch blocks to handle certain types of exceptions and you can use a finally block to make sure that certain code will always run. You should create a custom exception only if you expect developers to handle it or perform custom logging.
Custom logging can happen when you throw more detailed exceptions, so developers can differentiate between the errors that happen. Incorrect: Although the exception has to do with an argument to your method, you should throw the more specialized ArgumentNullException.
Incorrect: InvalidOperationException should be used when your class is not in the correct state to handle a request. Incorrect: NullReferenceException is thrown by the runtime when you try to refer- ence a null value. Correct: ArgumentNullException is the most specialized exception that you can use to tell which argument was null and what you expect. Incorrect: The Message property of an exception is read-only.
Correct: The new exception can contain extra info. Setting the InnerException makes sure that the original exception stays available. Incorrect: Throwing a brand-new exception loses the original exception and the information that it had. Correct answers: A, B, C A. Correct: You should always add a default empty constructor. Correct: A second constructor should take a descriptive message of why the error occurred. Correct: An InnerException can be set to correlate two exceptions and show what the original error was.
When building object- oriented software, types are your tools. Being skilled in creating useful types can make the difference between a successful project and a disaster.
C offers all the basic building blocks you need to create types that can be the foundation of any software project. In this chapter, you learn what C has to offer when it comes to creating types.
You learn how to create types that can be easily used by you and your coworkers, types that encapsu- late their inner workings so that you can focus on using them in the best way possible. After learning how to create types, you examine what it means for C to be a managed environment and how you can play nicely when using unmanaged, external resources. Finally, you look at how to use some of the types that the.
NET Framework offers, and you work with the built-in string type. Manipulate strings Objective 2. In C , there are a lot of options for creating a type. Knowing your options will enable you to choose and use those options wisely. For example, using enums can make your code a lot more readable. Using generics can make your code much more flexible and save you a lot of time. But with great power comes great responsibility. EPUB The open industry format known for its reflowable content and usability on supported mobile devices.
PDF The popular standard, which reproduces the look and layout of the printed page. This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.
About eBook formats. Prepare for Microsoft Exam , and demonstrate your real-world mastery of skills needed to build modern C applications. Learning paths to gain the skills needed to become certified.
Learning paths are not yet available for this exam. This training course teaches developers the programming skills that are required for developers to create Windows applications using the Visual C language.
During their five days in the classroom students review the basics of Visual C program structure, language syntax, and implementation details, and then consolidate their knowledge throughout the week as they build an application that incorporates several features of the. NET Framework 4. This course is not designed for students who are new to programming; it is targeted at professional developers with at least one month of experience programming in an object-oriented environment.
There may be certifications and prerequisites related to "Exam Programming in C ". This certification demonstrates your expertise at implementing Universal Windows Platform apps that offer a compelling user experience across a wide range of Windows devices.
See two great offers to help boost your odds of success. Review and manage your scheduled appointments, certificates, and transcripts. You need to create a LINQ query to meet the requirements. You need to ensure that if an exception occurs, the exception will be logged. Which code should you insert at line 28? You need to meet the requirements. You need to download an image named imagel. Which code should you use? You are creating a method that will be used in the game.
The method includes the following code. You need to ensure that the method meets the requirements. Which code segment should you insert at line 03?
The Game class must meet the following requirements: - Include a member that represents the score for a Game instance. You need to implement the score member to meet the requirements. In which form should you implement the score member?
What should you use? Answer: D Explanation: Member overloading means creating two or more members on the same type that differ only in the number or type of parameters but have the same name.
Overloading is one of the most important techniques for improving usability, productivity, and readability of reusable libraries. Overloading on the number of parameters makes it possible to provide simpler versions of constructors and methods. Overloading on the parameter type makes it possible to use the same member name for members performing identical operations on a selected set of different types. The application uses exception handling on a method that is used to execute mathematical calculations by using integer numbers.
You write the following catch blocks for the method line numbers are included for reference only :. You need to add the following code to the method: At which line should you insert the code?
You need to ensure that the ProcessData method performs the required actions. Which code segment should you use in the method body? IsCancellationRequested return; B. ThrowIfCancellationRequested ; D. The class is decorated with the DataContractAttribute attribute. The application includes the following code. You need to ensure that the entire FullName object is serialized to the memory stream object.
Which code segment should you insert at line 09? The following code implements the EmployeeRoster class.
0コメント