C# For Dummies
Chapter 12. Exception Handling
1. Find out all exceptions in the
System.IO.IOException
hierarchy.
Guidelines: Search in MSDN. The easiest way to do this is to search in Google for
"IOException MSDN" (without the quotes).
Solution:
Link
2. Find out all standard exceptions that are part of the
hierarchy holding the class
System.IO.FileNotFoundException
.
Guidelines: Look at the instructions for the
previous task.
Solution:
Link
3. Find out all standard exceptions from
System.ApplicationException
hierarchy.
Guidelines: Look at the instructions for the
previous task.
Solution:
Link
4. Write a program that takes a positive integer from the console and prints the
square root of this integer. If the input is
negative or invalid print \"Invalid Number\" in the console. In all cases print \"Good Bye\".
Guidelines: Create a
try{} - catch(){} - finally{}
statement.
Solution:
Link
5. Write a method
ReadNumber(int start, int end)
that reads an integer from the console in the range [start…end]. In case the input integer is not valid or it is not in the required range throw appropriate exception. Using this method, write a program that takes 10 integers
a1, a2, …, a10
such that
1 < a1 < … < a10 < 100
.
Guidelines: When invalid number is used we can throw
Exception
because there is no other exception that can better describe the problem. As an alternative we can define our own exception class called in a way that better describes the problem, e.g
InvalidNumberException
.
Solution:
Link
6. Write a method that takes as a parameter the name of a
text file, reads the file and returns its content as string
. What should the method do if and
exception is thrown?
Guidelines: Read the file line by line with
System.IO.StreamReader
class and add the rows in
System.Text.StringBuilder
. Throw all exceptions from the method without catching them. You may cheat and solve the problem in one line of code by using the static method
System.IO.File.ReadAllText()
.
Solution:
Link
7. Write a program that gets from the user the full path to a file (for example C:\\Windows\\win.ini), reads the content of the file and prints it to the console. Find in MSDN how to us the
System.IO.File.ReadAllText(…)
method. Make sure all possible exceptions will be caught and a user-friendly message will be printed on the console.
Guidelines: Search for all possible exceptions that the method could throw and for all of them define a
catch
block and print user-friendly message.
Solution:
Link
8. Write a program that
downloads a file from Internet by given URL, e.g. (http://www.devbg.org/img/Logo-BASD.jpg).
Guidelines: Search for articles in Internet for "
downloading a file with C#" or search for information and examples about using the WebClient class. Make sure you catch and process all
exceptions that can be thrown.
Solution:
Link
← Back