The sum of the valid numbers
A line contains words separated by spaces. Add up all the words that are whole numbers and count the ones that are not.
Example
Input
5 abc 12 7.5 -3 xOutput
Sum: 14
Invalid: 3An exception is an error that occurs while a program is running: the user enters letters instead of a number, a number is divided by zero, an element outside an array is requested… Without handling, an exception stops the program. The try and catch blocks let the program "catch" the error, handle it and keep running.
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
try
{
int x = int.Parse(Console.ReadLine()); // can throw a FormatException
Console.WriteLine($"100 / {x} = {100 / x}"); // can throw a DivideByZeroException
}
catch (FormatException)
{
Console.WriteLine("Error: that is not a whole number.");
}
catch (DivideByZeroException)
{
Console.WriteLine("Error: division by zero.");
}
Console.WriteLine("The program keeps running.");
}
}
When an exception occurs in the try block, the rest of the block is skipped and the first catch whose type matches is looked for. After the handling, the program continues after the whole try-catch. The most common exceptions are shown in the table:
| Exception | When it occurs |
|---|---|
FormatException | the text is not in the expected form (int.Parse("abc")) |
DivideByZeroException | integer division by zero |
IndexOutOfRangeException | an index outside the bounds of an array |
ArgumentOutOfRangeException | an index outside the bounds of a list or a string |
NullReferenceException | using a variable whose value is null |
KeyNotFoundException | reading a key that does not exist in a dictionary |
OverflowException | the number does not fit in the type (for example int.Parse("99999999999")) |
The finally block is executed always – both when there is no exception and when one has been caught. It is used for "cleaning up": closing a file, a database connection… After the type in catch you can write a variable name, and then you get the exception object with data about the error.
using System;
class Program
{
static void Main()
{
int[] array = { 10, 20, 30 };
for (int i = 2; i <= 3; i++)
{
try
{
Console.WriteLine($"array[{i}] = {array[i]}");
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine($"Caught exception: {e.GetType().Name}");
}
finally
{
Console.WriteLine($"finally for i = {i}");
}
}
}
}
The property e.Message contains a description of the error (in the language of the operating system), and catch (Exception e) catches an exception of any type – that is why it is written last, after the more specific ones.
Catching exceptions is slower and less clear than an ordinary check. When an error can be foreseen – such as wrong input – it is better to check in advance, for example with the TryParse method. Exceptions are for situations that cannot easily be checked.
using System;
class Program
{
// repeats the input until the user enters a whole number in the range [min, max]
static int ReadNumber(string message, int min, int max)
{
while (true)
{
Console.Write(message);
if (int.TryParse(Console.ReadLine(), out int x) && x >= min && x <= max)
return x;
Console.WriteLine($"Enter a whole number from {min} to {max}.");
}
}
static void Main()
{
int grade = ReadNumber("Grade: ", 1, 5);
Console.WriteLine($"Grade entered: {grade}");
}
}
Our own code can also throw an exception with the throw statement, when a method gets data it cannot work with. This way the method does not have to print messages itself – the error is reported to whoever called the method.
using System;
class Account
{
public decimal Balance { get; private set; }
public void Deposit(decimal amount) => Balance += amount;
public void Withdraw(decimal amount)
{
if (amount <= 0)
throw new ArgumentException("The amount must be positive.");
if (amount > Balance)
throw new InvalidOperationException($"Not enough money (balance: {Balance}).");
Balance -= amount;
}
}
class Program
{
static void Main()
{
var a = new Account();
a.Deposit(500);
decimal[] requests = { 200, -50, 1000, 300 };
foreach (decimal r in requests)
{
try
{
a.Withdraw(r);
Console.WriteLine($"Withdrawn {r}, balance {a.Balance}");
}
catch (ArgumentException e)
{
Console.WriteLine("Rejected: " + e.Message);
}
catch (InvalidOperationException e)
{
Console.WriteLine("Rejected: " + e.Message);
}
}
}
}
Your own exception is a class that inherits the class Exception. By convention its name ends with Exception, and the message is passed to the base class constructor with : base(message). The same approach is used in the advanced example with train passengers.
using System;
using System.Collections.Generic;
class CapacityExceededException : Exception
{
public int Capacity { get; }
public CapacityExceededException(int capacity)
: base($"The capacity of {capacity} seats has been exceeded.")
{
Capacity = capacity;
}
}
class Bus
{
private readonly List<string> passengers = new List<string>();
private readonly int capacity;
public Bus(int capacity) { this.capacity = capacity; }
public int Count => passengers.Count;
public void Board(string name)
{
if (passengers.Count == capacity)
throw new CapacityExceededException(capacity);
passengers.Add(name);
}
}
class Program
{
static void Main()
{
var bus = new Bus(3);
string[] line = { "Anna", "Bob", "Cindy", "Dan", "Emma" };
try
{
foreach (string name in line)
{
bus.Board(name);
Console.WriteLine($"{name} got on.");
}
}
catch (CapacityExceededException e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine($"On the bus: {bus.Count}");
}
}
}
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
A line contains words separated by spaces. Add up all the words that are whole numbers and count the ones that are not.
5 abc 12 7.5 -3 xSum: 14
Invalid: 3Each line of the input has the form a op b (whole numbers and an operation + - * /), and the input ends with the line end. For each line print the result (division is integer division) or the message Error: invalid number, Error: division by zero or Error: unknown operation X. Handle the errors with exceptions.
8 + 5
7 / 0
9 ^ 2
12 * x
20 / 6
end13
Error: division by zero
Error: unknown operation ^
Error: invalid number
3catch { } hides errors.catch blocks come before more general ones (catch (Exception) is last).TryParse is better than catching a FormatException.Exception, and the class inherits Exception.1. Which exception does int.Parse("abc") throw?
2. When is the finally block executed?
3. With which statement does a method report an error itself?
4. Which class does your own exception inherit?