Генерация ошибок

This commit is contained in:
Sem730 2022-11-22 13:30:05 +03:00
parent 665230d385
commit 5d9ccfb1db
5 changed files with 94 additions and 33 deletions

View File

@ -65,14 +65,25 @@ namespace ProjectLocomotive
{
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(locomotive) != -1)
try
{
MessageBox.Show("Объект добавлен");
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObject(locomotive) != -1)
{
MessageBox.Show("Object added");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Failed to add object");
}
}
else
catch(StorageOverflowException ex)
{
MessageBox.Show("Ошибка при добавлении объекта");
MessageBox.Show($"Storage overflow error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Unknown error: {ex.Message}");
}
}
/// Удаление объекта
@ -91,14 +102,25 @@ namespace ProjectLocomotive
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Object removed");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Failed to remove object");
}
}
else
catch (LocomotiveNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Delete error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Unknown error: {ex.Message}");
}
}
/// Вывод набора
@ -186,13 +208,14 @@ namespace ProjectLocomotive
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
MessageBox.Show("Saved successfully", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Saving success", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Saving failed", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Saving error: {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -200,16 +223,17 @@ namespace ProjectLocomotive
{
if (loadFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(loadFileDialog.FileName))
try
{
_mapsCollection.LoadData(loadFileDialog.FileName);
MessageBox.Show("Loaded successfully", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Loading failed", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
catch (Exception ex)
{
MessageBox.Show($"Loading failed + {ex.Message}", "Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ReloadMaps();
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive
{
internal class LocomotiveNotFoundException : ApplicationException
{
public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public LocomotiveNotFoundException() : base() { }
public LocomotiveNotFoundException(string message) : base(message) { }
public LocomotiveNotFoundException(string message, Exception exception) :
base(message, exception)
{ }
protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -52,7 +52,7 @@ namespace Locomotive
}
}
/// Сохранение информации по локомотивам в хранилище в файл
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -69,14 +69,13 @@ namespace Locomotive
);
}
}
return true;
}
/// Загрузка информации по локомотивам в депо из файла
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs, Encoding.UTF8))
@ -85,7 +84,7 @@ namespace Locomotive
if (!curLine.Contains("MapsCollection"))
{
return false;
throw new FileFormatException("Формат данных в файле неправильный");
}
_mapStorages.Clear();
while ((curLine = sr.ReadLine()) != null)
@ -105,11 +104,9 @@ namespace Locomotive
map = new RailroadMap();
break;
}
_mapStorages.Add(elems[0], new MapWithSetLocomotivesGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elems[0]].LoadData(elems[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}

View File

@ -33,16 +33,18 @@ namespace ProjectLocomotive
/// Добавление объекта в набор на конкретную позицию
public int Insert(T locomotive, int position)
{
if (position >= _maxCount || position < 0) return -1;
if (position < 0) return -1;
if (Count >= _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, locomotive);
return position;
}
/// Удаление объекта из набора с конкретной позиции
public T Remove(int position)
{
if (position >= _maxCount || position < 0) return null;
//if (position >= _maxCount || position < 0) return null;
if (_places[position] is null) throw new LocomotiveNotFoundException(position);
T result = _places[position];
_places.RemoveAt(position);
_places[position] = null;
return result;
}
// Индексатор
@ -68,10 +70,6 @@ namespace ProjectLocomotive
{
yield return locomotive;
}
else
{
yield break;
}
}
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLocomotive
{
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) :
base(message, exception)
{ }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}