官术网_书友最值得收藏!

Throw expressions

We also need to add the code to save a new storage space. Add the following code to the Click event of the btnSaveNewStorageSpace button:

private void btnSaveNewStorageSpace_Click(object sender,
EventArgs e) { try { if (txtNewStorageSpaceName.Text.Length != 0) { string newName = txtNewStorageSpaceName.Text; // throw expressions: bool spaceExists =
(space exists = false) ? return false : throw exception // Out variables bool spaceExists = (!spaces.StorageSpaceExists
(newName, out int nextID)) ? false : throw new
Exception("The storage space you are
trying to add already exists."); if (!spaceExists) { StorageSpace newSpace = new StorageSpace(); newSpace.Name = newName; newSpace.ID = nextID; newSpace.Description =
txtStorageSpaceDescription.Text; spaces.Add(newSpace); PopulateStorageSpacesList(); // Save new Storage Space Name txtNewStorageSpaceName.Clear(); txtNewStorageSpaceName.Visible = false; lblStorageSpaceDescription.Visible = false; txtStorageSpaceDescription.ReadOnly = true; txtStorageSpaceDescription.Clear(); btnSaveNewStorageSpace.Visible = false; btnCancelNewStorageSpaceSave.Visible = false; dlVirtualStorageSpaces.Enabled = true; btnAddNewStorageSpace.Enabled = true; } } } catch (Exception ex) { txtNewStorageSpaceName.SelectAll(); MessageBox.Show(ex.Message); } }

Here, we can see another new feature in the C# 7 language called throw expressions. This gives developers the ability to throw exceptions from expressions. The code in question is this code:

bool spaceExists = (!spaces.StorageSpaceExists(newName, out int nextID)) ? false : throw new Exception("The storage space you are trying to add already exists."); 

I always like to remember the structure of the code as follows:

The last few methods deal with saving eBooks in the selected Virtual Storage Space. Modify the Click event of the btnAddBookToStorageSpace button. This code also contains a throw expression. If you haven't selected a storage space from the combo box, a new exception is thrown:

private void btnAddeBookToStorageSpace_Click(object sender, EventArgs e) 
{ 
    try 
    { 
        int selectedStorageSpaceID = 
dlVirtualStorageSpaces.SelectedValue.ToString().ToInt(); if ((selectedStorageSpaceID !=
(int)StorageSpaceSelection.NoSelection)
&& (selectedStorageSpaceID !=
(int)StorageSpaceSelection.New)) { UpdateStorageSpaceBooks(selectedStorageSpaceID); } else throw new Exception("Please select a Storage
Space to add your eBook to"); // throw expressions } catch (Exception ex) { MessageBox.Show(ex.Message); } }

Developers can now immediately throw exceptions in code right there where they occur. This is rather nice and makes code cleaner and its intent clearer.

主站蜘蛛池模板: 深泽县| 淮安市| 海淀区| 鄢陵县| 壶关县| 大方县| 铁岭县| 旬邑县| 竹溪县| 隆安县| 都昌县| 宽城| 大竹县| 富源县| 太白县| 惠安县| 新干县| 龙陵县| 昆明市| 邯郸县| 泰兴市| 景东| 嫩江县| 咸宁市| 江陵县| 河东区| 敦煌市| 银川市| 黔江区| 德清县| 吐鲁番市| 平昌县| 浦东新区| 梓潼县| 汕头市| 洪湖市| 瓦房店市| 镇远县| 四子王旗| 浮梁县| 博罗县|