Answer the question
In order to leave comments, you need to log in
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)}>");
public string Top
{
get
{
return _elements.Last();
}
}
Answer the question
In order to leave comments, you need to log in
In general, throwing exceptions in properties is such a thing.
In your case, you should do this:
public string? Top => _elements.LastOrDefault(); // Обычный метод Last кидает исключение, если коллекция пустая
string? top = null;
try {
top = s.Top;
catch {}
Console.WriteLine($"Количество элементов в стеке: <{s.Size}>, верхний элемент стека: <{(top == null ? "null" : top)}>");
s.Top is {} t ? t : "null"
var msg = s switch {
{ Size: 0 } => $"Стек пуст",
{ Size: var size, Top: var top} => $"Количество элементов в стеке: <{size}>, верхний элемент стека: <{top}>"
};
Console.WriteLine(msg);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question