Putting it together
Combine all parts into a working final app.
Putting it all together
In the final lesson, we will combine all pieces inside Main. We will add two valid books, then try to add an invalid book and catch the error. Finally, we list the valid books with ListBooks. This synthesises the beginner level.
The program's output should be, in order: first the invalid book error is caught and printed, then ListBooks lists the two valid books that were added. Thanks to try/catch, the program continues without crashing and shows the books at the end.
Flow after try/catch
After the try/catch block completes, program flow continues normally. That is, after the catch block runs, the following statements are executed. This lets you catch an error and still run the program to the end.
In this project, after the try/catch block we call ListBooks();. Since the invalid book could not be added, the list holds only the two valid books; ListBooks prints those two. The user thus sees both the error and the list of valid books.
Exercise Assemble the program
Inside Main, set up this flow: first add two valid books with AddBook("The Lord of the Rings", 350); and AddBook("Crime and Punishment", 700);. Then try the invalid book with try { AddBook("Invalid Book", 0); } and catch (InvalidBookException ex) { Console.WriteLine("Error: " + ex.Message); }. Finally call ListBooks();.
Show example solution
" + ex.Message); } and ListBooks();
Example solution:
using System;
using System.Collections.Generic;
class Book
{
public string Title;
public int PageCount;
}
class InvalidBookException : Exception
{
public InvalidBookException(string msg) : base(msg) { }
}
class Program
{
static List<Book> books = new List<Book>();
static void PrintMenu()
{
Console.WriteLine("1 - Add");
Console.WriteLine("2 - List");
Console.WriteLine("3 - Exit");
}
static void AddBook(string title, int pageCount)
{
if (pageCount <= 0)
{
throw new InvalidBookException("Page count must be greater than zero");
}
books.Add(new Book { Title = title, PageCount = pageCount });
}
static void ListBooks()
{
foreach (Book b in books)
{
Console.WriteLine(b.Title + " - " + b.PageCount + " pages");
}
}
static void Main()
{
AddBook("The Lord of the Rings", 350);
AddBook("Crime and Punishment", 700);
try
{
AddBook("Invalid Book", 0);
}
catch (InvalidBookException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
ListBooks();
}
}
Test yourself
-
Match each step with its outcome
- Add a valid book
- Added to the list
- Add an invalid book
- Error is caught
- Call ListBooks
- Books are printed
-
What happens after try/catch?
try { AddBook("X", 0); } catch (InvalidBookException ex) { ... } ListBooks();- catch runs, then ListBooks is called
- The program crashes
- ListBooks is not called
- The try block runs again
Show answer
catch runs, then ListBooks is called — Correct! catch runs, flow continues and ListBooks is called.
-
List call
catch (Exception ex) { } ____;Show answer
catch (Exception ex) { } ListBooks();