Добавлен выброс исключений

This commit is contained in:
Никита Потапов 2023-12-18 23:57:27 +04:00
parent 5a12399986
commit 59a9be54ee
4 changed files with 48 additions and 23 deletions

View File

@ -7,5 +7,6 @@
</content> </content>
<orderEntry type="inheritedJdk" /> <orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="log4j-core-2_22_0" level="project" />
</component> </component>
</module> </module>

View File

@ -61,10 +61,19 @@ public class FormPlaneCollection {
fileChooser.setDialogTitle("Выберите файл для загрузки данных"); fileChooser.setDialogTitle("Выберите файл для загрузки данных");
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile(); File selectedFile = fileChooser.getSelectedFile();
if (_storage.LoadData(selectedFile.getAbsolutePath())) { try {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); if (_storage.LoadData(selectedFile.getAbsolutePath())) {
} else { JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE); } else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(
null,
"Ошибка при загрузке объектов" + ex.getMessage(),
"Результат",
JOptionPane.ERROR_MESSAGE
);
} }
} }
ReloadObjects(); ReloadObjects();
@ -78,10 +87,19 @@ public class FormPlaneCollection {
fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt")); fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt"));
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile(); File selectedFile = fileChooser.getSelectedFile();
if (_storage.SaveData(selectedFile.getAbsolutePath())) try {
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE); if (_storage.SaveData(selectedFile.getAbsolutePath()))
else JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE); else
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(
null,
"Ошибка при сохранении объектов" + ex.getMessage(),
"Результат",
JOptionPane.ERROR_MESSAGE
);
}
} }
} }
); );

View File

@ -71,7 +71,7 @@ public class PlanesGenericStorage {
return true; return true;
} }
public boolean LoadDataSingle(String filename){ public boolean LoadDataSingle(String filename) {
if (!new File(filename).exists()) { if (!new File(filename).exists()) {
return false; return false;
} }
@ -85,15 +85,14 @@ public class PlanesGenericStorage {
if (key == null || key.isEmpty()) if (key == null || key.isEmpty())
return false; return false;
PlanesGenericCollection<DrawingPlane, DrawingObjectPlane> collection; PlanesGenericCollection<DrawingPlane, DrawingObjectPlane> collection;
if (_planeStorages.containsKey(key)){ if (_planeStorages.containsKey(key)) {
collection = _planeStorages.get(key); collection = _planeStorages.get(key);
collection.clear(); collection.clear();
} } else
else
collection = new PlanesGenericCollection<>(_pictureWidth, _pictureHeight); collection = new PlanesGenericCollection<>(_pictureWidth, _pictureHeight);
List<String> plainsStrings = new ArrayList<>(); List<String> plainsStrings = new ArrayList<>();
s = reader.readLine(); s = reader.readLine();
while (s != null && !s.isEmpty()){ while (s != null && !s.isEmpty()) {
plainsStrings.add(s); plainsStrings.add(s);
s = reader.readLine(); s = reader.readLine();
} }
@ -107,7 +106,6 @@ public class PlanesGenericStorage {
); );
if (plane == null || collection.Add(plane) == -1) if (plane == null || collection.Add(plane) == -1)
return false; return false;
plane.SetDrawingBounds(1000, 1000);
} }
_planeStorages.put(key, collection); _planeStorages.put(key, collection);
} catch (IOException e) { } catch (IOException e) {
@ -116,7 +114,7 @@ public class PlanesGenericStorage {
return true; return true;
} }
public boolean SaveData(String filename) { public boolean SaveData(String filename) throws Exception {
var file = new File(filename); var file = new File(filename);
if (file.exists()) { if (file.exists()) {
file.delete(); file.delete();
@ -130,7 +128,7 @@ public class PlanesGenericStorage {
data.append(record.getKey()).append(_separatorForKeyValue).append(records).append("\n"); data.append(record.getKey()).append(_separatorForKeyValue).append(records).append("\n");
} }
if (data.isEmpty()) { if (data.isEmpty()) {
return false; throw new Exception("Невалидная операция, нет данных для сохранения");
} }
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(_keyword + System.lineSeparator() + data); writer.write(_keyword + System.lineSeparator() + data);
@ -140,18 +138,18 @@ public class PlanesGenericStorage {
return true; return true;
} }
public boolean LoadData(String filename) { public boolean LoadData(String filename) throws Exception {
var file = new File(filename); var file = new File(filename);
if (!file.exists()) { if (!file.exists()) {
return false; throw new Exception("Файл не найден");
} }
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) { try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String s = reader.readLine(); String s = reader.readLine();
if (s == null || s.isEmpty()) if (s == null || s.isEmpty())
return false; throw new Exception("Нет данных для загрузки");
if (!s.startsWith(_keyword)) { if (!s.startsWith(_keyword)) {
return false; throw new Exception("Неверный формат данных");
} }
_planeStorages.clear(); _planeStorages.clear();
s = reader.readLine(); s = reader.readLine();
@ -171,9 +169,11 @@ public class PlanesGenericStorage {
_separatorForObject, _separatorForObject,
_pictureWidth, _pictureHeight _pictureWidth, _pictureHeight
); );
if (plane == null || collection.Add(plane) == -1) if (plane != null) {
return false; if (collection.Add(plane) == -1) {
plane.SetDrawingBounds(1000, 1000); throw new Exception("Ошибка добавления в коллекцию");
}
}
} }
_planeStorages.put(record[0], collection); _planeStorages.put(record[0], collection);
} }

View File

@ -26,6 +26,9 @@ public class SetGeneric<T extends DrawingPlane> {
if (position < 0 || position >= _maxCount) { if (position < 0 || position >= _maxCount) {
return -1; return -1;
} }
if (Count() == _maxCount) {
throw new PlanesStorageOverflowException(_maxCount);
}
// Вставка по позиции // Вставка по позиции
_places.add(position, plane); _places.add(position, plane);
return position; return position;
@ -38,6 +41,9 @@ public class SetGeneric<T extends DrawingPlane> {
} }
// Удаление объекта из массива, присвоив элементу массива значение null // Удаление объекта из массива, присвоив элементу массива значение null
T plane = _places.get(position); T plane = _places.get(position);
if (plane == null) {
throw new PlaneNotFoundException(position);
}
_places.set(position, null); _places.set(position, null);
return plane; return plane;
} }