L
L
Ledington2021-09-23 08:34:12
C++ / C#
Ledington, 2021-09-23 08:34:12

How to catch an exception in a property and throw it out?

I can't figure out how to catch an exception in a property when the stack is empty.

There is a property call:

Console.WriteLine($"Количество элементов в стеке: <{s.Size}>, верхний элемент стека: <{(s.Top == null ? "null" : s.Top)}>");


The property itself:
public string Top
        {
            get
            {
                return _elements.Last();
            }
        }


But instead of displaying a normal message or anything else, it throws me an error with an InvalidOperationException exception.
How can I catch this exception and display my message?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-09-23
@Ledington

In general, throwing exceptions in properties is such a thing.
In your case, you should do this:

public string? Top => _elements.LastOrDefault(); // Обычный метод Last кидает исключение, если коллекция пустая

If this could not be done, we would have to wrap everything in a try-catch. For example like this:
string? top = null;
try {
  top = s.Top;
catch {}
Console.WriteLine($"Количество элементов в стеке: <{s.Size}>, верхний элемент стека: <{(top == null ? "null" : top)}>");

By the way, in order not to evaluate s.Top twice in a ternary, you can use pattern matching ; Another option is to leave everything as it is, but compose the message differently:
s.Top is {} t ? t : "null"
var msg = s switch {
  { Size: 0 } => $"Стек пуст",
  { Size: var size, Top: var top} => $"Количество элементов в стеке: <{size}>, верхний элемент стека: <{top}>"
};
Console.WriteLine(msg);

A
Alexander Ananiev, 2021-09-23
@SaNNy32

https://metanit.com/sharp/tutorial/2.14.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question