Java unchecked exception пример



Java Checked vs Unchecked Exceptions

Last Updated: December 20, 2022

In this Java exceptions tutorial, learn what an exception is in Java, and the difference between a checked exception and an unchecked exception. We will also learn some Java exception handling best practices.

1. What is Exception in Java?

“An exception is an unexpected event that occurred during the execution of a program, and disrupts the normal flow of instructions.”

  • In Java, all errors and exceptions are of type with Throwable class.
  • When an error occurs within a method, the method creates an object (or any subtype of Throwable ) and hands it off to the runtime system. This object is called the exception object.
  • The exception object contains information about the error, including the exception type and the program’s state when the error occurred.
  • Creating an exception object and handing it to the runtime system is called throwing an exception.

A few examples of an exception in the program execution can be:

  • The user enters alphanumeric input, and the program excepts numeric input.
  • The program tries to read the file, but the file does not exist in the specified location.
  • A network connection terminated while reading data from a webservice.

2. Handling a Thrown Exception

We have two choices when an exception object is created in our application;

  • Either we will handle it within the method using the try-catch block.
  • Or we can pass it to the caller method to let it handle.

This is a very important decision to be made while setting the responsibilities of a method.

A method should clearly indicate what exceptions it will handle and which it will not. It is defined in the method declaration using the throws keyword.

To handle the exception, We must catch the exception in catch section of try-catch block.

If an exception is not handled in the application, then it will propagate to the JVM. The JVM usually terminates the program.

3. Checked Exception vs Unchecked Exception

In Java, exceptions are broadly categorized into two sections:

  • Checked exceptions
  • Unchecked exceptions

3.1. Checked Exceptions

The checked exceptions are those exceptions, as the name suggests, which a method must handle in its body or throw to the caller method so the caller method can handle it.

Checked exceptions are checked by the Java compiler, so they are called compile-time exceptions.

Java compiler forces us to handle these exceptions in some manner in the application code. We must handle these exceptions at a suitable level inside the application to inform the user about the failure and ask him to retry or come later.

Generally, checked exceptions denote error scenarios outside the program’s immediate control. These usually occur when the program interacts with other systems/network resources e.g. database errors, network connection errors, missing files, etc.

Note that all checked exceptions are subclasses of Exception class. For example,

  • ClassNotFoundException
  • IOException
  • SQLException

Checked Exception Example

The FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the filesystem, Java forces us to handle an error situation where the file may not be present in the place.

In the above example, you will get compile-time error with the message – Unhandled exception type FileNotFoundException .

To make the program able to compile, we must handle this error situation in the try-catch block. Below given code will compile absolutely fine.

3.2. Unchecked Exception

Unchecked exceptions are not checked by the compiler. These are called runtime exceptions. Unchecked exceptions will come into life and occur in the program, once any buggy code is executed.

In Java, the compiler does not force a member method to declare the unchecked exceptions into the method declaration. Generally, such methods almost always do not declare them.

Unchecked Exceptions are subclasses of RuntimeException class.

  • ArithmeticException
  • ArrayStoreException
  • ClassCastException

The strange thing is that RuntimeException is itself subclass of Exception i.e. all unchecked exception classes should have been checked exceptions implicitly, BUT they are not.”

Unchecked Exception Example

The code in the given program does not give any compile-time error. But when we run the example, it throws NullPointerException . NullPointerException is an unchecked exception in Java.

4. Exception Handling Best Practices

  • Checked exceptions can be used when a method may fail to do what it must. For example, a method named prepareSystem() that pre-populates configuration files and does some configuration using them. It can declare throwing FileNotFoundException, which implies that the method uses configuration files from the file system and they are missing.
  • Ideally, checked exceptions should never be used for programming errors but should absolutely be used for resource errors and flow control in such cases.
  • Throw only those exceptions that a method can not handle by any means. The method should first try to handle it as soon as it encounters it. Throw the exception only if it is impossible to handle it inside the method.
  • A good way to define method signatures is to declare exceptions close to method name. If the method is named openFile() , then it is expected to throw FileNotFoundException ?. If the method is named findProvider() , then it is expected to throw NoSuchProviderException .
  • Also, these types of exceptions should be checked as it forces the caller to deal with the problems inherent to the semantics of the methods.
  • If we are creating any custom exception, then the rule is if a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Читайте также:  Ошибка при установке защитного соединения

5. Conclusion

In this Java tutorial, we learned about Java exceptions. We learned the difference between checked vs unchecked exceptions in Java and how to handle unchecked exceptions and exception hierarchy in Java with examples.

Remember, the biggest difference between checked and unchecked exceptions is that checked exceptions are forced by the compiler and used to indicate exceptional conditions that are out of the program’s control, while unchecked exceptions occur during runtime and are used to indicate programming errors.

Источник

How to Handle Checked & Unchecked Exceptions in Java

Table of Contents

Checked Exceptions in Java

In broad terms, a checked exception (also called a logical exception) in Java is something that has gone wrong in your code and is potentially recoverable. For example, if there’s a client error when calling another API, we could retry from that exception and see if the API is back up and running the second time. A checked exception is caught at compile time so if something throws a checked exception the compiler will enforce that you handle it.

Fig1: Types of Exceptions in Java, Checked vs Unchecked

Checked Exception Examples

The code below shows the FileInputStream method from the java.io package with a red line underneath. The red line is because this method throws a checked exception and the compiler is forcing us to handle it. You can do this in one of two ways.

Try Catch

You simply wrap the Java code which throws the checked exception within a try catch block. This now allows you to process and deal with the exception. With this approach it’s very easy to swallow the exception and then carry on like nothing happened. Later in the code when what the method was doing is required you may find yourself with our good friend the NullPointerException .

We have now caught the exception and processed the error in a meaningful way by adding our code to the catch block, the code sequence carries on crisis averted.

Throws

We use the keyword throws to throw the checked exception up the stack to the calling method to handle. This is what FileInputStream has just done to you. This looks and feels great — no messy exception code we are writing and we no longer need to handle this exception as someone else can deal with it. The calling method then needs to do something with it . maybe throw again.

As with try catch be wary of always throwing as you need to think who SHOULD be handling the error and what piece of code is best placed to handle it correctly.

Unchecked Exceptions in Java

An unchecked exception (also known as an runtime exception) in Java is something that has gone wrong with the program and is unrecoverable. Just because this is not a compile time exception, meaning you do not need to handle it, that does not mean you don’t need to be concerned about it.

The most common Java unchecked exception is the good old NullPointerException which is when you are trying to access a variable or object that doesn’t exist.

So to summarize; the difference between a checked and unchecked exception is that a checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, a runtime isn’t required to be handled. An unchecked exception is a programming error and are fatal, whereas a checked exception is an exception condition within your codes logic and can be recovered or retried from.

Unchecked Exception Examples

BindException

Because we live in a world where systems are built from lots of small micro services doing their own thing all talking to each other, generally over HTTP, this exception is popping up more and more. There isn’t a lot you can do about it other than find a free port. Only one system can use a single port at any one time and it’s on a first come, first serve basis. Most web applications default to port 8080 so the easiest option is to pick another one.

Читайте также:  Unable to start web server nested exception

IndexOutOfBoundsException

This is a very common Java unchecked exception when dealing with arrays. This is telling you; you have tried to access an index in an array that does not exist. If an array has 10 items and you ask for item 11 you will get this exception for your efforts.

The above piece of Java code is a common way to get an IndexOutOfBoundsException . The reason this trips people up is because the size of the array is 3 — makes sense; there are 3 items — but arrays are 0-based so the last item in the array is at index 2. To access the last item, it is always the size -1.

Checked Exceptions During Runtime

Below is an example that is very commonly used in micro service architecture. If we received a request and we cannot, say, read data from our database needed for this request, the database will throw us a checked exception, maybe an SQLException or something similar. Because this data is important, we cannot fulfil this request without it.

This means there is nothing we can actually do with this exception that can fix the problem, but if we do nothing the code will carry on its execution regardless.

We could throw the exception to the calling code until we get to the top of the chain and return the exception to the user. By doing that we are then littering all the layers above with an exception that they really do not care about, nor should they. What we really want is an unchecked exception to terminate this request gracefully.

Above we have our same piece of Java code for handling the checked exception thrown from the FileInputStream method but this time we are throwing our own RuntimeException and because this exception isn’t checked at compile time, we don’t need to declare it.

Declaring your own exception type is as simple as extending the runtime exception class because as we have seen from the diagram at the top, RuntimeException is a subtype of Exception.

Difference Between Checked and Unchecked Exceptions in Java

To summarize, the difference between a checked and unchecked exception is:

  • A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime.
  • A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn’t required to be handled.
  • A runtime exception is a programming error and is fatal whereas a checked exception is an exception condition within your code’s logic and can be recovered or re-tried from.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Источник

Исключения в Java, Часть II (checked/unchecked)

Это вторая часть статьи (первая часть — try-catch-finally), посвященной такому языковому механизму Java как исключения. Она имеет вводный характер и рассчитана на начинающих разработчиков или тех, кто только приступает к изучению языка.

Также я веду курс «Scala for Java Developers» на платформе для онлайн-образования udemy.com (аналог Coursera/EdX).

1. «Магия» checked/unchecked

Механизм исключительных ситуация в Java связан с двумя элементами «магии», т.е. поведения, которое никак не отражено в исходном коде:
1. «Магию» java.lang.Throwable — в throw, catch и throws могут стоять исключительно Throwable или его наследники (мы уже разбирали в предыдущей лекции). Это «право» находиться в throw, catch и throws никак не отражено в исходном коде.
2. Все исключительные ситуации делятся на «проверяемые» (checked) и «непроверяемые» (unchecked). Это свойство присуще «корневищу» (Throwable, Error, Exception, RuntimeException) и передается по наследству. Никак не видимо в исходном коде класса исключения.

В дальнейших примера просто учтите, что
— Throwable и Exception и все их наследники (за исключением наследников Error-а и RuntimeException-а) — checked
— Error и RuntimeException и все их наследники — unchecked

checked exception = проверяемое исключение, проверяемое компилятором.
Что именно проверяет компилятор мы разберем на этой лекции.

Напомним иерархию исключений

Расставим значение свойства checked/unchecked

2. Пессимистичный механизм

Я называю связь между проверяемыми исключениями и throws — «пессимистичной», польку мы можем «напугать» о большем, чем может произойти на самом деле, но не наоборот

Мы не можем бросать, но не предупредить

Читайте также:  Nfs most wanted runtime error

Мы не можем бросать, но предупредить о «меньшем»

Мы можем предупредить точно о том, что бросаем

Мы можем предупредить о большем, чем мы бросаем

Можем даже предупредить о том, чего вообще нет

Даже если предупреждаем о том, чего нет — все обязаны бояться

Хотя они (испугавшиеся) могут перепугать остальных еще больше

В чем цель «пессимистичности»? Все достаточно просто.
Вы в режиме протипирования «набросали», скажем, класс-утилиту для скачивания из интернета

и хотели бы «принудить» пользователей вашего класса УЖЕ ОБРАБАТЫВАТЬ возможное исключение IOException, хотя из реализации-пустышки вы ПОКА НЕ ГЕНЕРИРУЕТЕ такое исключение. Но в будущем — собираетесь.

3. throws с непроверяемым (unckecked) исключением

Вызов метода, который «пугает» unchecked исключением не накладывает на нас никаких обязанностей.

Эта конструкция служит цели «указать» программисту-читателю кода на то, что ваш метод может выбросить некоторое непроверяемое (unchecked) исключение.

Пример (java.lang.NumberFormatException — непроверяемое исключение):

Integer.parseInt() может бросить unchecked NumberFormatException на неподходящем аргументе (int k = Integer.parseInt(«123abc»)), это отразили
— в сигнатуре метода: throws NumberFormatException
— в документации (javadoc): @ exception
но это ни к чему нас не обязывает.

4. Множественные исключения

Рассмотрим ситуацию с кодом, который может бросать проверяемые исключения разных типов.
Далее учитывайте, что EOFException и FileNotFoundException — потомки IOException.

Мы можем точно указать, что выбрасываем

А можем «испугать» сильнее (предком обоих исключений)

Можно и вот так: EOFException и FileNotFoundException «обобщаем до» IOException, а InterruptedException «пропускаем нетронутым» (InterruptedException — НЕ потомок IOException)

5. Или catch, или throws

Не надо пугать тем, что вы перехватили
так

или так (ставим catch по предку и точно перехватываем)

Но если перехватили только потомка, то не выйдет

Не годится, естественно, и перехватывание «брата»

Если вы часть перехватили, то можете этим не пугать

6. Поведение компилятора/JVM

Необходимо понимать, что
проверка на cheched исключения происходит в момент компиляции (compile-time checking)
перехват исключений (catch) происходит в момент выполнения (runtime checking)

Полная аналогия с

Хотя ССЫЛКА ref УКАЗЫВАЕТ на объект типа java.lang.String (у которого имеется метод charAt(int)), но ТИП ССЫЛКИ — java.lang.Object (ссылка типа java.lang.Object на объект типа java.lang.String). Компилятор ориентируется на «левый тип» (тип ссылки, а не тип ссылаемого) и не пропускает такой код.

Хотя В ДАННОЙ СИТУАЦИИ компилятор мог бы разобрать, что t ссылается на Exception, а ref — на String, но этого уже невозможно сделать при раздельно компиляции. Представьте, что мы МОГЛИ БЫ скомпилировать ОТДЕЛЬНО такой класс, упаковать в jar и распространять

А кто-то берет этот класс, добавляет в classpath и вызывает App.f0(new Throwable()) или App.f1(new Integer(42)). В таком случае JVM столкнулась бы с ситуацией, когда от нее требует бросить проверяемое исключение, которое не отследил компилятор (в случае с f0) или вызвать метод, которого нет (в случае с f1)!

Java — язык со статической типизацией (т.е. отслеживание корректности использования типов (наличие используемых полей, наличие вызываемых методов, проверка на checked исключения, . ) проводится компилятором), запрещает такое поведение. В некоторых языках (языки с динамической типизацией — отслеживание корректности использования типов проводится средой исполнения (оно разрешено, например в JavaScript).

Компилятор не пропустит этот код, хотя метод main ГАРАНТИРОВАННО НЕ ВЫБРОСИТ ИСКЛЮЧЕНИЯ

7. Overriding и throws

При переопределении (overriding) список исключений потомка не обязан совпадать с таковым у предка.
Но он должен быть «не сильнее» списка предка:

Однако тут мы попытались «расширить тип» бросаемых исключений

Почему можно сужать тип, но не расширять?
Рассмотрим следующую ситуацию:

Внимательно посмотрите на этот пример — если бы потомок мог расширять тип бросаемого исключения предка, то те места которые «ждут» предка, а получают экземпляр «расширенного» потомка могли бы неконтролируемо выбрасывать проверяемые исключения

8. Передача свойства по наследству

Напомним иерархию исключений с расставленными флагами свойства checked/unchecked

Логика расположения свойства НЕ СВЯЗАНА С НАСЛЕДОВАНИЕМ. Эту логику мы рассмотрим позже (в следующих статьях).
Однако свойство checked/unchecked пользовательских классов исключений строится ИСКЛЮЧИТЕЛЬНО НА ОСНОВЕ НАСЛЕДОВАНИЯ.
Правило крайне простое:
1. Если исключение из списка Throwable, Error, Exception, RuntimeException — то твое свойство надо просто запомнить.
2. Если ты не из списка, то твое свойство равно свойству предка. Нарушить наследование тут нельзя.

Если мы породим потомков A, B, C, D, E, F, G, H, I, J, K, L которые следующим образом наследуются от «корневища» (Throwable, Error, Exception, RuntimeException), то значение их свойства checked/unchecked можно увидеть на схеме

Контакты

Я занимаюсь онлайн обучением Java (курсы программирования) и публикую часть учебных материалов в рамках переработки курса Java Core. Видеозаписи лекций в аудитории Вы можете увидеть на youtube-канале, возможно видео канала лучше систематизировано в этой статье.
Мой метод обучения состоит в том, что я

  1. показываю различные варианты применения
  2. строю усложняющуюся последовательность примеров по каждому варианту
  3. объясняю логику двигавшую авторами (по мере возможности)
  4. даю большое количество тестов (50-100) всесторонне проверяющее понимание и демонстрирующих различные комбинации
  5. даю лабораторные для самостоятельной работы

Данная статье следует пунктам #1 (различные варианты) и #2(последовательность примеров по каждому варианту).

Источник

Сайт для системных администраторов