Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

if (num1 == 0) {

ArithmeticException ex =

new ArithmeticException("Value of num1 cannot be 0.") {

HelpLink = "http://www.learn2develop.net"

};

throw ex;

}

Here's how you can modify the previous program by customizing the various existing exception classes:

class Program {

static void Main(string[] args) {

int num1, num2;

try {

Console.Write("Please enter the first number:");

num1 = int.Parse(Console.ReadLine());

Console.Write("Please enter the second number:");

num2 = int.Parse(Console.ReadLine());

Program myApp = new Program();

Console.WriteLine("The result of {0}/{1} is {2}", num1, num2,

myApp.PerformDivision(num1, num2));

} catch (DivideByZeroException ex) {

Console.WriteLine(ex.Message);

} catch (ArithmeticException ex) {

Console.WriteLine(ex.Message);

} catch (FormatException ex) {

Console.WriteLine(ex.Message);

} catch (Exception ex) {

Console.WriteLine(ex.Message);

}

Console.ReadLine();

}

private int PerformDivision(int num1, int num2) {

if (num1 == 0) {

ArithmeticException ex =

new ArithmeticException("Value of num1 cannot be 0.") {

HelpLink = "http://www.learn2develop.net"

};

throw ex;

}

if (num2 == 0) {

DivideByZeroException ex =

new DivideByZeroException("Value of num2 cannot be 0.") {

HelpLink = "http://www.learn2develop.net"

};

throw ex;

}

return num1 / num2;

}

}

Here's the output when different values are entered for num1and num2:

Please enter the first number:0

Please enter the second number:5

Value of num1 cannot be 0.

Please enter the first number:5

Please enter the second number:0

Value of num2 cannot be 0.

The finally Statement

By now you know that you can use the try-сatchblock to enclose potentially dangerous code. This is especially useful for operations such as file manipulation, user input, and so on. Consider the following example:

FileStream fs = null;

try {

//---opens a file for reading---

fs = File.Open(@"C:\textfile.txt", FileMode.Open, FileAccess.Read);

//---tries to write some text into the file---

byte[] data = ASCIIEncoding.ASCII.GetBytes("some text");

fs.Write(data, 0, data.Length);

//---close the file---

fs.Close();

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

}

//---an error will occur here---

fs = File.Open(@"C:\textfile.txt", FileMode.Open, FileAccess.Read);

Suppose that you have a text file named textfile.txtlocated in C:\. In this example program, you first try to open the file for reading. After that, you try to write some text into the file, which causes an exception because the file was opened only for reading. After the exception is caught, you proceed to open the file again. However, this fails because the file is still open (the fs.Close()statement within the tryblock is never executed because the line before it has caused an exception). In this case, you need to ensure that the file is always closed — with or without an exception. For this, you can use the finallystatement.

The statement(s) enclosed within a finallyblock is always executed, regardless of whether an exception occurs. The following program shows how you can use the finallystatement to ensure that the file is always closed properly:

FileStream fs = null;

try {

//---opens a file for reading---

fs = File.Open(@"C:\textfile.txt", FileMode.Open, FileAccess.Read);

//---tries to write some text into the file---

byte[] data = ASCIIEncoding.ASCII.GetBytes("1234567890");

fs.Write(data, 0, data.Length);

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

} finally {

//---close the file stream object---

if (fs != null) fs.Close();

}

//---this will now be OK---

fs = File.Open(@"C:\textfile.txt", FileMode.Open, FileAccess.Read);

One important thing about exception handling is that the system uses a lot of resources to raise an exception; thus, you should always try to prevent the system from raising exceptions. Using the preceding example, instead of opening the file and then writing some text into it, it would be a good idea to first check whether the file is writable before proceeding to write into it. If the file is read-only, you simply inform the user that the file is read-only. That prevents an exception from being raised when you try to write into it.

The following shows how to prevent an exception from being raised:

FileStream fs = null;

try {

//---opens a file for reading---

fs = File.Open(@"C:\textfile.txt", FileMode.Open, FileAccess.Read);

//---checks to see if it is writeable---

if (fs.CanWrite) {

//---tries to write some text into the file---

byte[] data = ASCIIEncoding.ASCII.GetBytes("1234567890");

fs.Write(data, 0, data.Length);

} else Console.WriteLine("File is read-only");

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

} finally {

//---close the file stream object---

if (fs != null) fs.Close();

}

Creating Custom Exceptions

The .NET class libraries provide a list of exceptions that should be sufficient for most of your uses, but there may be times when you need to create your own custom exception class. You can do so by deriving from the Exceptionclass. The following is an example of a custom class named AllNumbersZeroException:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

public class AllNumbersZeroException : Exception {

public AllNumbersZeroException() {}

public AllNumbersZeroException(string message) : base(message) {}

public AllNumbersZeroException(string message, Exception inner) : base(message, inner) {}

}

To create your own custom exception class, you need to inherit from the Exceptionbase class and implement the three overloaded constructors for it.

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x