Catching and Handling Exceptions
This section describes how to use the three exception handler components — the try , catch , and finally blocks — to write an exception handler. Then, the try-with-resources statement, introduced in Java SE 7, is explained. The try-with-resources statement is particularly suited to situations that use Closeable resources, such as streams.
The last part of this section walks through an example and analyzes what occurs during various scenarios.
The following example defines and implements a class named ListOfNumbers . When constructed, ListOfNumbers creates an ArrayList that contains 10 Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList() , which writes the list of numbers into a text file called OutFile.txt . This example uses output classes defined in java.io , which are covered in the Basic I/O section.
The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an IOException . The second boldface line is a call to the ArrayList class's get method, which throws an IndexOutOfBoundsException if the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by the ArrayList .
If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor. However, it does not display an error message about the exception thrown by get() . The reason is that the exception thrown by the constructor, IOException , is a checked exception, and the one thrown by the get() method, IndexOutOfBoundsException , is an unchecked exception.
Now that you're familiar with the ListOfNumbers class and where the exceptions can be thrown within it, you're ready to write exception handlers to catch and handle those exceptions.
The Try Block
The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:
The segment in the example labeled code contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)
To construct an exception handler for the writeList() method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList() method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList() code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.
If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it; the next section, The catch Blocks, shows you how.
The Catch Blocks
You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.
The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.
The following are two exception handlers for the writeList() method:
Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the Chained Exceptions section.
Multi-Catching Exceptions
You can catch more than one type of exception with one exception handler, with the multi-catch pattern.
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar ( | ):
Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final . In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
The Finally Block
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break . Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute.
The try block of the writeList() method that you've been working with here opens a PrintWriter . The program should close that stream before exiting the writeList() method. This poses a somewhat complicated problem because writeList() 's try block can exit in one of three ways.
- The new FileWriter statement fails and throws an IOException .
- The list.get(i) statement fails and throws an IndexOutOfBoundsException .
- Everything succeeds and the try block exits normally.
The runtime system always executes the statements within the finally block regardless of what happens within the try block. So it's the perfect place to perform cleanup.
The following finally block for the writeList() method cleans up and then closes the PrintWriter .
Important: The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.
Consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. The try-with-resources Statement section has more information.
The Try-with-resources Statement
The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable , can be used as a resource.
The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:
In this example, the resource declared in the try-with-resources statement is a BufferedReader . The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader , in Java SE 7 and later, implements the interface java.lang.AutoCloseable . Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine() throwing an IOException .
Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:
However, in this example, if the methods readLine() and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock() throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile() , if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile() throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.
You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:
In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter . When the block of code that directly follows it terminates, either normally or because of an exception, the close() methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.
The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:
The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.
Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.
Suppressed Exceptions
An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents() , an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents() method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed() method from the exception thrown by the try block.
Classes That Implement the AutoCloseable or Closeable Interface
See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close() method of the Closeable interface throws exceptions of type IOException while the close() method of the AutoCloseable interface throws exceptions of type Exception . Consequently, subclasses of the AutoCloseable interface can override this behavior of the close() method to throw specialized exceptions, such as IOException , or no exception at all.
Putting It All Together
The previous sections described how to construct the try , catch , and finally code blocks for the writeList() method in the ListOfNumbers class. Now, let's walk through the code and investigate what can happen.
When all the components are put together, the writeList() method looks like the following.
As mentioned previously, this method's try block has three different exit possibilities; here are two of them.
- Code in the try statement fails and throws an exception. This could be an IOException caused by the new FileWriter statement or an IndexOutOfBoundsException caused by a wrong index value in the for loop.
- Everything succeeds and the try statement exits normally.
Let's look at what happens in the writeList() method during these two exit possibilities.
Scenario 1: An Exception Occurs
The statement that creates a FileWriter can fail for a number of reasons. For example, the constructor for the FileWriter throws an IOException if the program cannot create or write to the file indicated.
When FileWriter throws an IOException , the runtime system immediately stops executing the try block; method calls being executed are not completed. The runtime system then starts searching at the top of the method call stack for an appropriate exception handler. In this example, when the IOException occurs, the FileWriter constructor is at the top of the call stack. However, the FileWriter constructor doesn't have an appropriate exception handler, so the runtime system checks the next method — the writeList() method — in the method call stack. The writeList() method has two exception handlers: one for IOException and one for IndexOutOfBoundsException .
The runtime system checks writeList() 's handlers in the order in which they appear after the try statement. The argument to the first exception handler is IndexOutOfBoundsException . This does not match the type of exception thrown, so the runtime system checks the next exception handler — IOException . This matches the type of exception that was thrown, so the runtime system ends its search for an appropriate exception handler. Now that the runtime has found an appropriate handler, the code in that catch block is executed.
After the exception handler executes, the runtime system passes control to the finally block. Code in the finally block executes regardless of the exception caught above it. In this scenario, the FileWriter was never opened and doesn't need to be closed. After the finally block finishes executing, the program continues with the first statement after the finally block.
Here's the complete output from the ListOfNumbers program that appears when an IOException is thrown.
Scenario 2: The try Block Exits Normally
In this scenario, all the statements within the scope of the try block execute successfully and throw no exceptions. Execution falls off the end of the try block, and the runtime system passes control to the finally block. Because everything was successful, the PrintWriter is open when control reaches the finally block, which closes the PrintWriter . Again, after the finally block finishes executing, the program continues with the first statement after the finally block.
Here is the output from the ListOfNumbers program when no exceptions are thrown.
Что такое исключение?
Событие, которое встречается в ходе программы и прерывает стандартный ход её выполнения.
Исключение в Java – объект, экземпляр класса. Могут порождаться не только автоматически при возникновении исключительной ситуации, но и создаваться самим разработчиком. Все классы исключений наследуются от Throwable (имеют свойство – возможность быть брошенными через слово throw).
Throwable имплементирует Serializable
Иерархия исключений

Исключения имеют общего предка — класс Throwable, потомками которого являются классы Exception и Error.
Error — это критическая ошибка во время исполнения программы, связанная с работой виртуальной машины Java. Error это ошибки виртуальной машины.
В большинстве случаев Error не нужно обрабатывать, поскольку она свидетельствует о каких-то серьезных недоработках в коде.
StackOverflowError — возникает, например, когда метод бесконечно вызывает сам себя;
OutOfMemoryError — возникает, когда недостаточно памяти для создания новых объектов;
NoClassDefFoundError – не смог найти класс.
Исключения (Exceptions) являются результатом проблем в программе, которые в принципе решаемые и предсказуемые.
Например, произошло деление на ноль в целых числах. RuntimeExceptions исключения, которые могут быть предотвращены программно.
Расскажите про обрабатываемые и необрабатываемые исключения?
В Java все исключения делятся на два типа:
- checked (контролируемые/проверяемые исключения) должны обрабатываться блоком catch или описываться в сигнатуре метода (например, throws IOException). Наличие такого обработчика/модификатора сигнатуры проверяются на этапе компиляции;
- unchecked (неконтролируемые/непроверяемые исключения), к которым относятся ошибки Error, обрабатывать которые не рекомендуется, и исключения времени выполнения, представленные классом RuntimeException и его наследниками;
RuntimeExceptions:
- ArithmeticException — исключение, возникающее при делении на ноль
- IndexOutOfBoundException — тип индекса вышел за допустимые пределы
- IllegalArgumentException — использование неверного аргумента при вызове метода
- NullPointerException — использование пустой ссылки
- NumberFormatException — ошибка преобразования строки в число
- ArrayIndexOutOfBoundsException — выход за пределы массива
- FileNotFoundException – не нашел файл для открытия
- AccessDeniedException
- SocketException
- BindException
- ConnectException
Обработка исключений
Можно ли обработать необрабатываемые исключения?
Можно, но не надо.
Какой оператор позволяет принудительно выбросить исключение?
throw new Exception();
О чем говорит ключевое слово throws ?
Модификатор throws прописывается в сигнатуре метода и указывает на то, что метод потенциально может выбросить исключение с указанным типом
Как создать собственное («пользовательское») исключение?
Необходимо унаследоваться от базового класса требуемого типа исключений (например от Exception или RuntimeException).
Что произойдет если исключение будет выброшено из блока catch после чего другое исключение будет выброшено из блока finally?
Из finally подавит из catch будет обработано в finally блоке.
Одно в try, второе в finally, то исключение в finally проглотит исключение.
Если до блока finally исключение было обработано, то мы можем получить информацию об исключении в блоке try и тем самым не потерять исключение, которое впоследствии может быть перезаписано в finally другим исключением.
Механизм Try-catch-finally
try — данное ключевое слово используется для отметки начала блока кода, который потенциально может привести к ошибке.
catch — ключевое слово для отметки начала блока кода, предназначенного для перехвата и обработки исключений в случае их возникновения.
finally — ключевое слово для отметки начала блока кода, который является дополнительным. Этот блок помещается после последнего блока catch.
Управление передаётся в блок finally в любом случае, было выброшено исключение или нет.
Общий вид конструкции для обработки исключительной ситуации выглядит следующим образом:
//код, который потенциально может привести к исключительной ситуации
//код обработки исключительной ситуации
//необязательный блок, код которого выполняется в любом случае
Возможно ли использование блока try-finally (без catch)
Может ли один блок catch отлавливать сразу несколько исключений?
Всегда ли выполняется блок finally? Существуют ли ситуации, когда блок finally не будет выполнен?
Не будет выполнен когда:
- Когда System.exit(0) вызывается из блока try.
- Когда JVM исчерпывает память catch (OutOfMemoryError oome) < // do stuff >
- Когда ваш java-процесс принудительно убит из задачи или консоли
- Условие взаимоблокировки потоков в блоке try
- Когда ваш компьютер отключается из-за сбоя питания
Может ли метод main() выбросить исключение во вне и если да, то где будет происходить обработка данного исключения?
Может и оно будет передано в виртуальную машину Java (JVM).
В каком порядке следует обрабатывать исключения в catch блоках?
Общее правило: обрабатывать исключения нужно от «младшего» к старшему.
Т.е. нельзя поставить в первый блок catch(Exception ex) <>, иначе все дальнейшие блоки catch() уже ничего не смогут обработать, т.к. любое исключение будет соответствовать обработчику catch(Exception ex).
Механизм Try-With-Resources
Конструкцию try-with-resources ввели в Java 7. Она дает возможность объявлять один или несколько ресурсов в блоке try, которые будут закрыты автоматически без использования finally блока.
В качестве ресурса можно использовать любой объект, класс которого реализует интерфейс java.lang.AutoCloseable или java.io.Closable.
Если try блок также выбрасывает исключение, оно побеждает, а исключение из close() метода подавляется.
Использование блока finally для закрытия ресурса
public static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException <
BufferedReader br = new BufferedReader(new FileReader(path));
Использование конструкции try-with-resources для закрытия ресурса
public static String readFirstLineFromFile(String path) throws IOException <
try (BufferedReader br = new BufferedReader(new FileReader(path))) <
Использование конструкции try-with-resources для закрытия нескольких ресурсов
public static String readFirstLineFromFile2(String path) throws IOException <
What throws an IOException in Java?
java.io.IOException seems to be the most common type of exception, and coincidentally, it seems to also be the most ambiguous.
I keep seeing the throws IOException whenever writing with sockets, files, etc. I’ve never actually had one fired on me, however, so I’m wondering what it is that is supposed to fire the exception. The documentation isn’t very helpful in explaining what’s going on:
Signals that an I/O exception of some sort has occurred. This class is the general class of exceptions produced by failed or interrupted I/O operations.
What are some instances where an IOException would be thrown, and how is it supposed to be used?
![]()
3 Answers 3
Assume you were:
- Reading a network file and got disconnected.
- Reading a local file that was no longer available.
- Using some stream to read data and some other process closed the stream.
- Trying to read/write a file, but don’t have permission.
- Trying to write to a file, but disk space was no longer available.
There are many more examples, but these are the most common, in my experience.
![]()
In general, I/O means Input or Output. Those methods throw the IOException whenever an input or output operation is failed or interpreted. Note that this won’t be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException .
- Reading from a closed inputstream
- Try to access a file on the Internet without a network connection
![]()
Java documentation is helpful to know the root cause of a particular IOException.
Just have a look at the direct known sub-interfaces of IOException from the documentation page:
ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException
Most of these exceptions are self-explanatory.
A few IOExceptions with root causes:
EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.
SocketException: Thrown to indicate that there is an error creating or accessing a Socket.
RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.
UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).
MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
Исключения в Java: перехват и обработка

Для работы с исключениями в Java существуют специальные блоки кода: try , catch и finally . Код, в котором программист ожидает возникновения исключений, помещается в блок try . Это не значит, что исключение в этом месте обязательно произойдет. Это значит, что оно может там произойти, и программист в курсе этого. Тип ошибки, который ты ожидаешь получить, помещается в блок catch (“перехват”). Сюда же помещается весь код, который нужно выполнить, если исключение произойдет. Вот пример: Вывод: Мы поместили наш код в два блока. В первом блоке мы ожидаем, что может произойти ошибка “Файл не найден”. Это блок try . Во втором — указываем программе что делать, если произошла ошибка. Причем ошибка конкретного вида — FileNotFoundException . Если мы передадим в скобки блока catch другой класс исключения, оно не будет перехвачено. Вывод: Код в блоке catch не отработал, потому что мы “настроили” этот блок на перехват ArithmeticException , а код в блоке try выбросил другой тип — FileNotFoundException . Для FileNotFoundException мы не написали сценарий, поэтому программа вывела в консоль ту информацию, которая выводится по умолчанию для FileNotFoundException . Здесь тебе нужно обратить внимание на 3 вещи. Первое. Как только в какой-то строчке кода в блоке try возникнет исключение, код после нее уже не будет выполнен. Выполнение программы сразу “перепрыгнет” в блок catch . Например: Вывод: В блоке try во второй строчке мы попытались разделить число на 0, в результате чего возникло исключение ArithmeticException . После этого строки 6-10 блока try выполнены уже не будут. Как мы и говорили, программа сразу начала выполнять блок catch . Второе. Блоков catch может быть несколько. Если код в блоке try может выбросить не один, а несколько видов исключений, для каждого из них можно написать свой блок catch . В этом примере мы написали два блока catch . Если в блоке try произойдет FileNotFoundException , будет выполнен первый блок catch . Если произойдет ArithmeticException , выполнится второй. Блоков catch ты можешь написать хоть 50. Но, конечно, лучше не писать код, который может выбросить 50 разных видов ошибок 🙂 Третье. Откуда тебе знать, какие исключения может выбросить твой код? Ну, про некоторые ты, конечно, можешь догадываться, но держать все в голове невозможно. Поэтому компилятор Java знает о самых распространенных исключениях и знает, в каких ситуациях они могут возникнуть. Например, если ты написал код и компилятор знает, что при его работе могут возникнуть 2 вида исключений, твой код не скомпилируется, пока ты их не обработаешь. Примеры этого мы увидим ниже. Теперь что касается обработки исключений. Существует 2 способа их обработки. С первым мы уже познакомились — метод может обработать исключение самостоятельно в блоке catch() . Есть и второй вариант — метод может выбросить исключение вверх по стеку вызовов. Что это значит? Например, у нас в классе есть метод — все тот же printFirstString() , который считывает файл и выводит в консоль его первую строку: На текущий момент наш код не компилируется, потому что в нем есть необработанные исключения. В строке 1 ты указываешь путь к файлу. Компилятор знает, что такой код легко может привести к FileNotFoundException . В строке 3 ты считываешь текст из файла. В этом процессе легко может возникнуть IOException — ошибка при вводе-выводе данных (Input-Output). Сейчас компилятор говорит тебе: “Чувак, я не одобрю этот код и не скомпилирую его, пока ты не скажешь мне, что я должен делать в случае, если произойдет одно из этих исключений. А они точно могут произойти, исходя из того кода, который ты написал!”. Деваться некуда, нужно обрабатывать оба! Первый вариант обработки нам уже знаком: надо поместить наш код в блок try , и добавить два блока catch : Но это не единственный вариант. Мы можем не писать сценарий для ошибки внутри метода, и просто пробросить исключение наверх. Это делается с помощью ключевого слова throws , которое пишется в объявлении метода: После слова throws мы через запятую перечисляем все виды исключений, которые этот метод может выбросить при работе. Зачем это делается? Теперь, если кто-то в программе захочет вызвать метод printFirstString() , он должен будет сам реализовать обработку исключений. К примеру, в другой части программы кто-то из твоих коллег написал метод, внутри которого вызывает твой метод printFirstString() : Ошибка, код не компилируется! В методе printFirstString() мы не написали сценарий обработки ошибок. Поэтому задача ложится на плечи тех, кто будет этот метод использовать. То есть перед методом yourColleagueMethod() теперь стоят те же 2 варианта: он должен или обработать оба исключения, которые ему “прилетели”, с помощью try-catch , или пробросить их дальше. Во втором случае обработка ляжет на плечи следующего по стэку метода — того, который будет вызывать yourColleagueMethod() . Вот поэтому такой механизм называется “пробрасыванием исключения наверх”, или “передачей наверх”. alt=»Исключения: перехват и обработка — 3″ width=»1024″ />Когда ты пробрасываешь исключения наверх с помощью throws , код компилируется. Компилятор в этот момент как бы говорит: “Окей, ладно. Твой код содержит кучу потенциальных исключений, но я, так и быть, его скомпилирую. Мы еще вернемся к этому разговору!” И когда ты где-то в программе вызываешь метод, который не обработал свои исключения, компилятор выполняет свое обещание и снова напоминает о них. В завершении мы поговорим о блоке finally (простите за каламбур). Это последняя часть триумвирата обработки исключений try-catch-finally . Его особенность в том, что он выполняется при любом сценарии работы программы. В этом примере код внутри блока finally выполняется в обоих случаях. Если код в блоке try выполнится целиком и не выбросит исключения, в конце сработает блок finally . Если код внутри try прервется, и программа перепрыгнет в блок catch , после того, как отработает код внутри catch , все равно будет выбран блок finally . Зачем он нужен? Его главное назначение — выполнить обязательную часть кода; ту часть, которая должна быть выполнена независимо от обстоятельств. Например, в нем часто освобождают какие-то используемые программой ресурсы. В нашем коде мы открываем поток для чтения информации из файла и передаем его в объект BufferedReader . Наш reader нужно закрыть и освободить ресурсы. Это нужно сделать в любом случае: неважно, отработает программа как надо или вызовет исключение. Это удобно делать в блоке finally : Теперь мы точно уверены, что позаботились о занятых ресурсах независимо от того, что произойдет при работе программы 🙂 Это еще не все, что тебе нужно знать об исключениях. Обработка ошибок — очень важная тема в программировании: ей посвящена не одна статья. На следующем занятии мы узнаем, какие бывают виды исключений и как создать свое собственное исключение:) До встречи!