Как корректно реализовать вызов ошибки с помощью try catch в функции?

Рейтинг: 0Ответов: 3Опубликовано: 07.02.2023

В методах present и absent если длина массива this.visitinMagazine > 25 должно выбрасывать ошибку и удалять последний элемент массива, но этого не происходит. Подскажите как реализовать.

Методы present и absent:

class Visit extends Student {
    constructor(firstName, lastName, yearOfBirth, arrayOfGrades) {
        super(firstName, lastName, yearOfBirth, arrayOfGrades);
        this.visitinMagazine = [];
    }
    //______Используется когда студент был на занятие______//
    present () {
        try {
            if (this.visitinMagazine.length > 25) {
                throw new Error(`Обучение Happy End`)
                return this.visitinMagazine.pop();
            } else {
                this.visitinMagazine.push(true);
                return this;
            }
        } catch (error) {
            console.error(`Проверьте посещение ${this.firstName} ${error}`)
        }

    }
    //______Используется когда студент НЕ был на занятие______//
    absent () {
        try {
            if (this.visitinMagazine.length > 25) {
                throw new Error(`Обучение Happy End`)
                return this.visitinMagazine.pop();
            } else {
                this.visitinMagazine.push(false);
                return this;
            }
        } catch (error) {
            console.error(`Проверьте посещение ${this.firstName} ${error}`)
        }
    }
}

Общий код:

class Student {
    constructor(firstName,lastName,yearOfBirth,arrayOfGrades) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.yearOfBirth = yearOfBirth;
        this.arrayOfGrades = arrayOfGrades;
        this.age = new Date().getFullYear() - this.yearOfBirth;
        this.avgMark = arrayOfGrades.reduce((sum,item) => {
            return sum += item
        }, 0) / arrayOfGrades.length;

    }
    //______Возраст студента______//
    getAge () {
        const currentYear = new Date().getFullYear();
        try {
            if (this.yearOfBirth < 1900 || this.yearOfBirth >= currentYear) {
                throw new Error('Год рождения студента указан неверно')
            } else {
                return (`${this.firstName}'s old is ${this.age} years`);
            }
        } catch (error) {
            console.error(`Исправьте год рождения ${this.firstName} ${error}`)
        }
    }
    //______Средний бал______//
    averageMark () {
        try {
            if (this.avgMark > 100 || this.avgMark < 0) {
                throw new Error('Оценка расчитана неверно')
            } else {
                return(`${this.firstName}'s average mark is ${this.avgMark}`);
            }
        } catch (error) {
            console.log(`Проверьте правильность ввода данных ${this.firstName} ${error}`)
        }
    }
}

class Visit extends Student {
    constructor(firstName, lastName, yearOfBirth, arrayOfGrades) {
        super(firstName, lastName, yearOfBirth, arrayOfGrades);
        this.visitinMagazine = [];
    }
    //______Используется когда студент был на занятие______//
    present () {
        try {
            if (this.visitinMagazine.length > 25) {
                throw new Error(`Обучение Happy End`)
                return this.visitinMagazine.pop();
            } else {
                this.visitinMagazine.push(true);
                return this;
            }
        } catch (error) {
            console.error(`Проверьте ппосещение ${this.firstName} ${error}`)
        }

    }
    //______Используется когда студент НЕ был на занятие______//
    absent () {
        try {
            if (this.visitinMagazine.length > 25) {
                throw new Error(`Обучение Happy End`)
                return this.visitinMagazine.pop();
            } else {
                this.visitinMagazine.push(false);
                return this;
            }
        } catch (error) {
            console.error(`Проверьте посещение ${this.firstName} ${error}`)
        }
    }
}

 class Calculation extends Visit {
    constructor(firstName, lastName, yearsOfBirth, arrayOfGrades) {
        super(firstName, lastName, yearsOfBirth, arrayOfGrades);
    }

     //______Проверяем среднюю оценку и посейщение______//
     summary () {
         const averageVisit = this.visitinMagazine.filter((element) => element === true).length / this.visitinMagazine.length;
         if (this.avgMark > 90 && averageVisit > 0.9) {
             return 'Cool!';
         } else if (this.avgMark > 90 || averageVisit > 0.9) {
            return 'Good, but it can be better!';
         } else {
             return 'Radish';
         }
     }
 }
//______Экземпляры расчетов______//
const calculate = new Calculation('Dmitriy', 'Yaroshchuk', 2001, [70, 80, 90, 100, 90, 90, 99, 100, 95, 100]);
const calculate1 = new Calculation('Andrew', 'Kavetsky', 2000, [90, 90, 90, 90, 90, 90, 100, 100, 95, 93]);
const calculate2 = new Calculation('Diana', 'Koko', 1999, [70, 70, 70, 70, 70, 70, 75, 75, 75, 93]);

console.log(calculate.getAge());
console.log(calculate1.getAge());
console.log(calculate2.getAge());

console.log(calculate.averageMark());
console.log(calculate1.averageMark());
console.log(calculate2.averageMark());


//______Посейщение уроков______//
calculate.present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().absent().absent().absent();

//______Посейщение уроков______//
calculate1.absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().absent().present().present();

//______Посейщение уроков______//
calculate2.present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().present().absent().absent().absent().absent().absent();

console.log(calculate.visitinMagazine);
console.log(calculate1.visitinMagazine);
console.log(calculate2.visitinMagazine);

console.log(calculate.summary());
console.log(calculate1.summary());
console.log(calculate2.summary());


if (typeof module === 'object') {
    module.exports = { Calculation: Calculation, calculate: calculate }
}

Ответы

▲ 1Принят
  1. После throw другие инструкции не выполняются

  2. Ты должен возвращать this

     present() {
       try {
         if (this.visitinMagazine.length > 25) {
           throw new Error("");
         } else {
           this.visitinMagazine.push(true);
           return this;
         }
       } catch (error) {
         this.visitinMagazine.pop();
         return this;
       }
     }
    

и absent()

absent() {
      try {
        if (this.visitinMagazine.length > 25) {
          throw new Error("");
        } else {
          this.visitinMagazine.push(false);
          return this;
        }
      } catch (error) {
        this.visitinMagazine.pop();
        return this;
      }
    }
▲ 1

Вариант первый, не совсем по заданию, но правильный
Переделываем методы в такую конструкцию

absent () {
    if (this.visitinMagazine.length < 25) {
        this.visitinMagazine.push(false);
        return true;
    }
    this.visitinMagazine.pop();
    throw new Error(`Обучение для ${this.firstName} Happy End`)
}

Вызов методов делаем не цепочкой(что в целом было изначально не правильно), а в цикле, т.е. студент приходит каждый день, а не после (не)прихода предыдущего

for (let i = 0; i < 50; i++) {
    try {
        calculate1.absent();
    } catch (e) {
        console.error('Студент протух: ', e)
        break;
    }
}

В цикле приходов ставим try catch, что бы отловить ошибку, т.к. мы ее там возможно ожидаем.

Если по заданию реализовывать, то тут почти то же самое

absent() {
    try {
        if (this.visitinMagazine.length < 25) {
            this.visitinMagazine.push(false);
            return true;
        }
        throw new Error('Много пропусков')
    } catch (e) {
        this.visitinMagazine.pop();
        throw new Error(`Обучение для ${this.firstName} Happy End`)
    }
}

Внутри блока try генерим исключение, если количество посещений больше 25. Это исключение попадает в блок catch, из которого мы передаем ошибку туда, откуда вызван данный метод. Соответственно, ошибку надо там так же перехватывать.

Такая же логика должна действовать для метода present()

▲ 0

Инструкция throw позволяет генерировать исключения, определяемые пользователем. При этом выполнение текущей функции будет остановлено (инструкции после throw не будут выполнены), и управление будет передано в первый блок catch в стеке вызовов.

Поэтому return this.visitinMagazine.pop() не срабатывает. Перенеси этот return после throw в catch

present () {
    try {
        if (this.visitinMagazine.length > 25) {
            throw new Error(`Обучение Happy End`)
        } else {
            this.visitinMagazine.push(true);
            return this;
        }
    } catch (error) {
        console.error(`Проверьте посещение ${this.firstName} ${error}`);
        this.visitinMagazine.pop();
        return this;
    }
}

В функции absent тоже самое. Инструкции после throw не выполняются, поэтому перенеси в catch.