Difference between exception and error

I'm trying to learn more about basic Java and the different types of Throwables, can someone let me know the differences between Exceptions and Errors?

I’m trying to learn more about basic Java and the different types of Throwables, can someone let me know the differences between Exceptions and Errors?

Termininja's user avatar

Termininja

6,44212 gold badges46 silver badges49 bronze badges

asked May 26, 2009 at 19:39

Marco Leung's user avatar

Errors should not be caught or handled (except in the rarest of cases). Exceptions are the bread and butter of exception handling. The Javadoc explains it well:

An Error is a subclass of Throwable that indicates serious problems that a
reasonable application should not try to catch. Most such errors are abnormal
conditions.

Look at a few of the subclasses of Error, taking some of their JavaDoc comments:

  • AnnotationFormatError — Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.
  • AssertionError — Thrown to indicate that an assertion has failed.
  • LinkageError — Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
  • VirtualMachineError — Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.

There are really three important subcategories of Throwable:

  • Error — Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,
  • Unchecked Exception (aka RuntimeException) — Very often a programming error such as a NullPointerException or an illegal argument. Applications can sometimes handle or recover from this Throwable category — or at least catch it at the Thread’s run() method, log the complaint, and continue running.
  • Checked Exception (aka Everything else) — Applications are expected to be able to catch and meaningfully do something with the rest, such as FileNotFoundException and TimeoutException

answered May 26, 2009 at 19:43

Eddie's user avatar

EddieEddie

53.5k22 gold badges124 silver badges144 bronze badges

2

Errors tend to signal the end of your application as you know it. It typically cannot be recovered from and should cause your VM to exit. Catching them should not be done except to possibly log or display and appropriate message before exiting.

Example:
OutOfMemoryError
— Not much you can do as your program can no longer run.

Exceptions are often recoverable and even when not, they generally just mean an attempted operation failed, but your program can still carry on.

Example:
IllegalArgumentException
— Passed invalid data to a method so that method call failed, but it does not affect future operations.

These are simplistic examples, and there is another wealth of information on just Exceptions alone.

answered May 26, 2009 at 19:47

Robin's user avatar

RobinRobin

23.9k4 gold badges49 silver badges58 bronze badges

1

Errors —

  1. Errors in java are of type java.lang.Error.
  2. All errors in java are unchecked type.
  3. Errors happen at run time. They will not be known to compiler.
  4. It is impossible to recover from errors.
  5. Errors are mostly caused by the environment in which application is running.
  6. Examples : java.lang.StackOverflowError, java.lang.OutOfMemoryError

Exceptions —

  1. Exceptions in java are of type java.lang.Exception.
  2. Exceptions include both checked as well as unchecked type.
  3. Checked exceptions are known to compiler where as unchecked exceptions are not known to compiler because they occur at run time.
  4. You can recover from exceptions by handling them through try-catch blocks.
  5. Exceptions are mainly caused by the application itself.
  6. Examples : Checked Exceptions : SQLException, IOException
    Unchecked Exceptions : ArrayIndexOutOfBoundException, ClassCastException, NullPointerException

further reading : http://javaconceptoftheday.com/difference-between-error-vs-exception-in-java/
http://javaconceptoftheday.com/wp-content/uploads/2015/04/ErrorVsException.png

answered Sep 15, 2017 at 6:19

roottraveller's user avatar

roottravellerroottraveller

7,7247 gold badges58 silver badges65 bronze badges

Sun puts it best:

An Error is a subclass of Throwable
that indicates serious problems that a
reasonable application should not try
to catch.

answered May 26, 2009 at 19:48

Powerlord's user avatar

PowerlordPowerlord

86.5k17 gold badges125 silver badges172 bronze badges

The description of the Error class is quite clear:

An Error is a subclass of Throwable
that indicates serious problems that a
reasonable application should not try
to catch. Most such errors are
abnormal conditions. The ThreadDeath
error, though a «normal» condition, is
also a subclass of Error because most
applications should not try to catch
it.

A method is not required to declare in
its throws clause any subclasses of
Error that might be thrown during the
execution of the method but not
caught, since these errors are
abnormal conditions that should never
occur.

Cited from Java’s own documentation of the class Error.

In short, you should not catch Errors, except you have a good reason to do so. (For example to prevent your implementation of web server to crash if a servlet runs out of memory or something like that.)

An Exception, on the other hand, is just a normal exception as in any other modern language. You will find a detailed description in the Java API documentation or any online or offline resource.

answered May 26, 2009 at 19:50

Tobias Müller's user avatar

There is several similarities and differences between classes java.lang.Exception and java.lang.Error.

Similarities:

  • First — both classes extends java.lang.Throwable and as a result
    inherits many of the methods which are common to be used when dealing
    with errors such as: getMessage, getStackTrace, printStackTrace and
    so on.

  • Second, as being subclasses of java.lang.Throwable they both inherit
    following properties:

    • Throwable itself and any of its subclasses (including java.lang.Error) can be declared in method exceptions list using throws keyword. Such declaration required only for java.lang.Exception and subclasses, for java.lang.Throwable, java.lang.Error and java.lang.RuntimeException and their subclasses it is optional.

    • Only java.lang.Throwable and subclasses allowed to be used in the catch clause.

    • Only java.lang.Throwable and subclasses can be used with keyword — throw.

The conclusion from this property is following both java.lang.Error and java.lang.Exception can be declared in the method header, can be in catch clause, can be used with keyword throw.

Differences:

  • First — conceptual difference: java.lang.Error designed to be
    thrown by the JVM and indicate serious problems and intended to stop
    program execution instead of being caught(but it is possible as for
    any other java.lang.Throwable successor).

    A passage from javadoc description about java.lang.Error:

    …indicates serious problems that a reasonable application should
    not try to catch.

    In opposite java.lang.Exception designed to represent errors that
    expected and can be handled by a programmer without terminating
    program execution.

    A passage from javadoc description about java.lang.Exception:

    …indicates conditions that a reasonable application might want to
    catch.

  • The second difference between java.lang.Error and java.lang.Exception that first considered to be a unchecked exception for compile-time exception checking. As the result code throwing java.lang.Error or its subclasses don’t require to declare this error in the method header. While throwing java.lang.Exception required declaration in the method header.

Throwable and its successor class diagram (properties and methods are omitted).
enter image description here

answered May 4, 2016 at 14:59

Mikhailov Valentin's user avatar

IMO an error is something that can cause your application to fail and should not be handled. An exception is something that can cause unpredictable results, but can be recovered from.

Example:

If a program has run out of memory it is an error as the application cannot continue. However, if a program accepts an incorrect input type it is an exception as the program can handle it and redirect to receive the correct input type.

answered May 26, 2009 at 19:50

Mr. Will's user avatar

Mr. WillMr. Will

2,3083 gold badges21 silver badges27 bronze badges

Errors are mainly caused by the environment in which application is running. For example, OutOfMemoryError occurs when JVM runs out of memory or StackOverflowError occurs when stack overflows.

Exceptions are mainly caused by the application itself. For example, NullPointerException occurs when an application tries to access null object or ClassCastException occurs when an application tries to cast incompatible class types.

Source : Difference Between Error Vs Exception In Java

answered Apr 27, 2015 at 14:10

user2485429's user avatar

user2485429user2485429

5778 silver badges7 bronze badges

1

Here’s a pretty good summary from Java API what an Error and Exception represents:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a «normal» condition, is also a subclass of Error because most applications should not try to catch it.

A method is not required to declare in
its throws clause any subclasses of
Error that might be thrown during the
execution of the method but not
caught, since these errors are
abnormal conditions that should never
occur.

OTOH, for Exceptions, Java API says:

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

answered May 26, 2009 at 19:50

egaga's user avatar

egagaegaga

20.7k10 gold badges45 silver badges60 bronze badges

Errors are caused by the environment where your application or program runs. Most times, you may not recover from it as this ends your application or program. Javadoc advised that you shouldn’t bother catching such errors since the environment e.g. JVM, on such errors is going to quit anyway.

Examples:
VirtualMachineError — Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
OutOfMemoryError occurs when JVM runs out of memory or
StackOverflowError occurs when stack runs over.

Exceptions are caused by your application or program itself; maybe due to your own mistake. Most times you can recover from it and your application would still continue to run. You are advised to catch such errors to prevent abnormal termination of your application or program and/or to be able to customize the exception message so the users see a nicely formatted message instead of the default ugly exception messages scattered all over the place.

Examples:
NullPointerException occurs when an application tries to access null object. or
Trying to access an array with a non-existing index or calling a function with wrong data or parameters.

answered May 19, 2020 at 10:12

pasignature's user avatar

pasignaturepasignature

5651 gold badge6 silver badges13 bronze badges

Exceptions and errors both are subclasses of Throwable class. The error indicates a problem that mainly occurs due to the lack of system resources and our application should not catch these types of problems. Some of the examples of errors are system crash error and out of memory error. Errors mostly occur at runtime that’s they belong to an unchecked type. 

Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers.  Exceptions are divided into two categories such as checked exceptions and unchecked exceptions. 

Sr. No. Key Error Exception
1 Type  Classified as an unchecked type  Classified as checked and unchecked 
2 Package  It belongs to java.lang.error  It belongs to java.lang.Exception 
3 Recoverable/ Irrecoverable It is irrecoverable It is recoverable
  It can’t be occur at compile time  It can occur at run time compile time both 
5 Example OutOfMemoryError ,IOError  NullPointerException , SqlException 

Example of Error

public class ErrorExample {
   public static void main(String[] args){
      recursiveMethod(10)
   }
   public static void recursiveMethod(int i){
      while(i!=0){
         i=i+1;
         recursiveMethod(i);
      }
   }
}

Output

Exception in thread "main" java.lang.StackOverflowError
   at ErrorExample.ErrorExample(Main.java:42)

Example of Exception

public class ExceptionExample {
   public static void main(String[] args){
      int x = 100;
      int y = 0;
      int z = x / y;
   }
}

Output

java.lang.ArithmeticException: / by zero
   at ExceptionExample.main(ExceptionExample.java:7)

Error-exception1“Throwable” act as the root for Java’s error and exception hierarchy. “Error” is a critical condition that cannot be handled by the code of the program. “Exception” is the exceptional situation that can be handled by the code of the program.

The significant difference between error and exception is that an error is caused due to lack of system resources, and an exception is caused because of your code. Let us study other differences between error and exception along with a comparison chart.

Content: Error Vs Exception

  1. Comparison Chart
  2. Definition
  3. Key Differences
  4. Conclusion

Comparison Chart

Basis for Comparison Error Exception
Basic An error is caused due to lack of system resources. An exception is caused because of the code.
Recovery An error is irrecoverable. An exception is recoverable.
Keywords There is no means to handle an error by the program code. Exceptions are handled using three keywords «try», «catch», and «throw».
Consequences As the error is detected the program will terminated abnormally. As an exception is detected, it is thrown and caught by the «throw» and «catch» keywords correspondingly.
Types Errors are classified as unchecked type. Exceptions are classified as checked or unchecked type.
Package In Java, errors are defined «java.lang.Error» package. In Java, an exceptions are defined in»java.lang.Exception».
Example OutOfMemory, StackOverFlow. Checked Exceptions : NoSuchMethod, ClassNotFound.
Unchecked Exceptions : NullPointer, IndexOutOfBounds.

Definition of Error

Error” is a subclass of the built-in class “Throwable”. Errors are the critical conditions that occur due to the lack of the system resources, and it can not be handled by the code of the program. Errors can not be recovered by any means because they can not be created, thrown, caught or replied.  Errors are caused due to the catastrophic failure which usually can not be handled by your program.

Errors are always of unchecked type, as compiler do not have any knowledge about its occurrence. Errors always occur in the run-time environment. The error can be explained with the help of an example, the program has an error of stack overflow, out of memory error, or a system crash error, this kind of error are due to the system.

The code is not responsible for such errors. The consequence of the occurrence of the error is that the program gets terminated abnormally.

Definition of Exception

“Exception” is also a subclass of built-in class “Throwable”. Exceptions are the exceptional conditions that occur in a runtime environment. Most of the times exceptions are caused due to the code of our program. But, exceptions can be handled by the program itself, as exceptions are recoverable. Exceptions are handled by using three keywords “try”, “catch”, “throw”. The syntax of writing an exception is:

try {
//write your code here
} Catch (Exception type) {
//write your code here
}

In above code, the code written in the try block is the code which you want to monitor for the exception. If the exception occurs in a try block, it is thrown using the “throw” keyword. The exception thrown can be caught by the “catch” block of the above code. “Exception type”  is the type of the exception that has occurred.

In simple words we can say that the mistakes occurred due to the improper code are called exceptions. For example, if a requested class is not found, or a requested method is not found. These kinds of exceptions are due to the code in the program; the system is not responsible for these kinds of exceptions.

The exceptions are classified as the “checked” and “unchecked”. Unchecked exceptions are not in knowledge of compiler as they occur during runtime whereas, the compiler has the knowledge about checked exceptions as they are known to compiler during compile time.

  1. Error occur only when system resources are deficient whereas, an exception is caused if a code has some problem.
  2. An error can never be recovered whereas, an exception can be recovered by preparing the code to handle the exception.
  3. An error can never be handled but, an exception can be handled by the code if the code throwing an exception is written inside a try and catch block.
  4. If an error has occurred, the program will be terminated abnormally. On the other hand, If the exception occurs the program will throw an exception, and it is handled using the try and catch block.
  5. Errors are of unchecked type i.e. error are not in the knowledge of compilers whereas, an exception is classified as checked and unchecked.
  6. Errors are defined in java.lang.Error package whereas, an exception is defined java.lang.Exception.

Conclusion

Exceptions are the results of mistakes done in the coding of the program, and the errors are the result of the improper functioning of the system

In Java, java.lang.Exception and java.lang.Error belong to the class java.lang.Throwable class. However, there are some basic differences that exist in between these two sub-classes. While errors are represented by the java.lang.Error class, especially the ones attributed to the runtime environment of the application, java.lang.Exception class considers the exceptions attributed to the application itself. In this article, we shall discuss the definitions and features of Error and Exception in Java, the difference between Exception and Error, etc. Read on to begin with a comparative chart showcasing the main differences between Error and exception in Java.

Error vs Exception

Basis of differentiation

Error

Exception

Type

Errors representing Java are of the type java.lang.Error.

Exceptions represented by Java are of the type java.lang.Exception.

Checked or unchecked

The Errors found in java are of the unchecked type.

The Exceptions found in java are of both types – unchecked and checked.

Timing

In Java, the Errors occur at run time. These errors cannot be found by the compiler.

The checked exceptions in Java are in the knowledge of the compiler. However, the compiler fails to have any information of the unchecked exceptions as they take place at run time.

Possibility of recovery

It is not possible or Java programs to gain recovery from errors.

Proper handling with the help of try-catch blocks can help programs recover from Exceptions in Java.

Caused by

Errors are mainly attributed to the runtime environment of an application.

The application itself is the main cause of Exceptions.

Examples

java.lang.OutOfMemoryError and java.lang.StackOverflowError

Checked Exceptions can be found as IOException, SQLException, etc.
The examples of unchecked exceptions are ArrayIndexOutOfBoundException, NullPointerException, ClassCastException, etc.

What is Error in JAVA

An Error in Java is usually indicative of a serious problem that can be fatal, and it is best for a reasonable application to not attempt to catch the same. It is a subclasses belonging to the java.lang.Throwable class in Java. As Errors pertain to conditions that are impossible to recover from via the usual handling techniques, abnormal termination of a program/ application serves to be the only way out. The Errors in the unchecked type category are mostly found at runtime. The striking instances of Errors in Java are Out of Memory Error, System Crash Error, etc.

What is Exception in JAVA

Exceptions in Java are events occurring during the time of program execution. Once they take place, the normal flow of related instructions is disrupted in the form of “array access out of bound”, “divide by zero”, etc. coming to the fore as Exceptions. An Exception in java relates to an object encapsulating an error event that takes place within a method; it usually contains the following:

1) Information pertaining to the error along with its type

2) Other customized information

3) The status of the application/ program at the time of the error taking place, etc.

The Exception objects are capable of being thrown and caught. They are useful for indicating the different kinds of error conditions. Some examples of Exceptions are FileNotFoundException, SocketTimeoutException, IOException, ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException, etc.

Key Difference between Exception and Error

The key differences between Exception and Error in Java are enumerated below:

1) Recovery from errors is impossible in Java programs. The only way to handle an error is by terminating the execution of the application. On the other hand, it is possible for an application to recover from an exception by throwing the exception back to the caller, or via try-catch blocks.

2) Errors in Java are incapable of being handled with the help of try-catch blocks. Even if the try-catch blocks are used for the purpose, the application will fail to recover. Conversely, once the try-catch blocks are used for handling Exceptions the program starts flowing normally once they happen.

3) The Errors in Java are undivided and belong to a singular category – checked. On the other hand, there are two categories of Exceptions in Java- Checked and unchecked.

4) As the sub classes of RunTimeException and Errors in Java are prone to taking place during runtime, the compiler fails to have any knowledge about their existence.
Therefore, the unchecked exceptions and Errors are likely to go unnoticed by the compiler. On the other hand, the information about checked Exceptions is present with the Java compiler. In turn, the compiler forces the user to implement try-catch blocks on the lines that may throw checked exceptions.

Conclusion

Error and Exception are both subclasses of Class Throwable. Regardless of this, in most cases, an Error is thrown back by the JVM. The scenario created is fatal as the application or program will not be able to recover from that Error e.g. OutOfMemoryError. A checked Exception comes to the knowledge of the Java compiler and can be handled. In case you have any further questions with respect to the differences between Error and Exception handling in Java then do get back to us in the Comments section below. We shall provide answers to your concerns at the earliest.

è¿éåå¾çæè¿°
Есть много причин для исключения, обычно включая следующие категории:

Пользователь ввел недопустимые данные.
Открываемый файл не существует.
Соединение было прервано во время сетевого взаимодействия или переполнена память JVM.
Некоторые из этих исключений вызваны ошибками пользователя, некоторые — ошибками программы, а другие — физическими ошибками. —

Чтобы понять, как работает обработка исключений Java, вам необходимо освоить следующие три типа исключений:

Проверенные исключения: наиболее характерными проверяемыми исключениями являются те, которые вызваны ошибками или проблемами пользователя, которые не могут быть предвидены программистами. Например, при открытии несуществующего файла возникает исключение, которое нельзя просто игнорировать во время компиляции.
Исключения времени выполнения. Исключения времени выполнения — это исключения, которых программисты могут избежать. В отличие от проверенных исключений, исключения времени выполнения можно игнорировать во время компиляции.
Ошибка. Ошибка — это не исключение, а проблема, не зависящая от программиста. Ошибки в коде обычно игнорируются. Например, при переполнении стека возникает ошибка, и их невозможно проверить при компиляции. Чтобы
Из рисунка видно, что все типы исключений являются подклассами встроенного класса Throwable, поэтому Throwable находится на вершине иерархии классов исключений.
Затем Throwable разделен на две разные ветви, одна из которых — Error, что означает, что вы не хотите, чтобы программа вас перехватила, или это ошибки, которые программа не может обработать. Другая ветвь — это исключение, которое представляет ненормальную ситуацию, которую может уловить пользовательская программа, или исключение, которое программа может обработать. Среди них Exception делится на исключение времени выполнения (RuntimeException) и исключение не во время выполнения.

Исключения Java можно разделить на непроверенное исключение и проверенное исключение.

Различия и связи между этими исключениями будут подробно описаны ниже:

Error:Объект класса Error создается Java
Виртуальная машина создается и создается. Большинство ошибок не имеют ничего общего с операциями, выполняемыми автором кода. Например, ошибка работы виртуальной машины Java (Virtual
MachineError), когда у JVM больше нет ресурсов памяти, необходимых для продолжения операции, он появится
OutOfMemoryError. Когда возникают эти исключения, виртуальная машина Java (JVM) обычно выбирает поток для завершения; и когда виртуальная машина пытается выполнить приложение, например, ошибка определения класса (NoClassDefFoundError), ошибка связи (LinkageError). Эти ошибки нельзя проверить, поскольку они связаны с возможностями управления и обработки приложения.
, и большинство из них не разрешены во время работы программы. В случае хорошо спроектированного приложения, даже если ошибка все же возникает, оно не должно по существу пытаться справиться с ненормальной ситуацией, которую оно вызывает. В Java ошибки обычно описываются с помощью подкласса Error.
Exception:В ветви Exception есть важный подкласс RuntimeException. Этот тип исключения автоматически определяет ArrayIndexOutOfBoundsException (индекс массива выходит за границы), NullPointerException (исключение нулевого указателя), ArithmeticException (арифметическое исключение), MissingResourceException (отсутствует ресурс), ClassNotFoundException (не удается найти класс) и другие исключения, эти исключения не являются проверенными исключениями, программа может выбрать захват обработки или не обрабатывать. Эти исключения обычно вызваны логическими ошибками программы.Программы должны избегать таких исключений, насколько это возможно с логической точки зрения; исключения, отличные от RuntimeException, вместе называются исключениями, не относящимися к среде выполнения, которые принадлежат классу Exception и его подклассам. С точки зрения синтаксиса программы это исключение, которое необходимо обработать. Если оно не обработано, программа не может быть скомпилирована. Такие как IOException, SQLException и т. Д. И определяемые пользователем исключения Exception обычно не настраивают исключения проверки.

è¿éåå¾çæè¿° 

1. В try {} есть оператор возврата, затем будет выполнен код в finally {} сразу после попытки. Когда он будет выполнен, до или после возврата?
Ответ: он будет выполнен до того, как метод вернется к вызывающему. Чтобы
2. Как язык Java обрабатывает исключения? Как использовать ключевые слова: throws, throw, try, catch и, наконец,?

Ответ: Java использует объектно-ориентированные методы для обработки исключений, классифицирует различные исключения и предоставляет хороший интерфейс. В Java каждое исключение — это объект, который является экземпляром класса Throwable или его подклассов. Когда в методе возникает исключение, создается объект исключения. Объект содержит информацию об исключении. Метод, вызывающий этот объект, может перехватить исключение и обработать его. Обработка исключений Java достигается с помощью пяти ключевых слов: try, catch, throw, throws и finally. Как правило, try используется для выполнения программы. Если система генерирует объект исключения, его можно поймать по его типу или обработать, всегда выполняя блок кода (наконец); используется try Чтобы указать программу для предотвращения всех исключений; предложение catch сразу после блока try используется для указания типа исключения, которое вы хотите перехватить; оператор throw используется для явного генерирования исключения; throws используется для объявления того, что метод может вызывать Всевозможные исключения (конечно, при объявлении исключений разрешены стоны); наконец, чтобы гарантировать, что часть кода выполняется независимо от того, какие аномальные условия возникают; операторы try могут быть вложенными, всякий раз, когда встречается оператор try, аномальная структура будет Войдите в стек исключений, пока не будут выполнены все операторы try. Если оператор try следующего уровня не обрабатывает исключение, стек исключений будет выполнять операцию pop до тех пор, пока не встретит оператор try, который обрабатывает это исключение, или, наконец, не вызовет исключение для JVM.

3. В чем сходство и различие между исключениями времени выполнения и проверенными исключениями?

Ответ: Аномалии указывают на ненормальные условия, которые могут возникнуть во время работы программы. Исключения во время выполнения указывают на аномалии, которые могут возникнуть при нормальной работе виртуальной машины. Это обычная операционная ошибка и обычно не возникает, если программа разрабатывается без проблем. Отмеченное исключение связано с контекстом, в котором выполняется программа. Даже если программа спроектирована правильно, это все равно может быть вызвано проблемами в использовании. Компилятор Java требует, чтобы методы объявляли генерирующие проверенные исключения, которые могут возникнуть, но не требует, чтобы они объявляли генерирование неперехваченных исключений времени выполнения. Исключениями, такими как наследование, часто злоупотребляют в объектно-ориентированном программировании. Следующие рекомендации приведены для использования исключений в Effective Java:
-Не используйте обработку исключений для обычного потока управления (хорошо спроектированный API не должен заставлять вызывающего его использовать исключения для обычного потока управления)
— использовать отмеченные исключения для исправимых ситуаций и исключения времени выполнения для ошибок программирования.
— Избегайте ненужного использования отмеченных исключений (можно использовать некоторые методы определения состояния, чтобы избежать исключений)
— присвоить приоритет стандартным исключениям
— исключения, создаваемые каждым методом, должны быть задокументированы.
-Сохранение атомарности исключений
— Не игнорировать перехваченное исключение в catch
 

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    In java, both Errors and Exceptions are the subclasses of java.lang.Throwable class. Error refers to an illegal operation performed by the user which results in the abnormal working of the program. Programming errors often remain undetected until the program is compiled or executed. Some of the errors inhibit the program from getting compiled or executed. Thus errors should be removed before compiling and executing. It is of three types:

    • Compile-time
    • Run-time
    • Logical

    Whereas exceptions in java refer to an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

    Now let us discuss various types of errors in order to get a better understanding over arrays. As discussed in the header an error indicates serious problems that a reasonable application should not try to catch. Errors are conditions that cannot get recovered by any handling techniques. It surely causes termination of the program abnormally. Errors belong to unchecked type and mostly occur at runtime. Some of the examples of errors are Out of memory errors or System crash errors. 

    Example 1 Run-time Error

    Java

    class StackOverflow {

        public static void test(int i)

        {

            if (i == 0)

                return;

            else {

                test(i++);

            }

        }

    }

    public class GFG {

        public static void main(String[] args)

        {

            StackOverflow.test(5);

        }

    }

    Output: 

    Example 2

    Java

    class GFG {

        public static void main(String args[])

        {

            int a = 2, b = 8, c = 6;

            if (a > b && a > c)

                System.out.println(a

                                   + " is the largest Number");

            else if (b > a && b > c)

                System.out.println(b

                                   + " is the smallest Number");

            else

                System.out.println(c

                                   + " is the largest Number");

        }

    }

    Output

    8 is the smallest Number

    Now let us dwell onto Exceptions which indicates conditions that a reasonable application might want to catch. Exceptions are the conditions that occur at runtime and may cause the termination of the program. But they are recoverable using try, catch and throw keywords. Exceptions are divided into two categories:

    • Checked exceptions
    • Unchecked exceptions

    Checked exceptions like IOException known to the compiler at compile time while unchecked exceptions like ArrayIndexOutOfBoundException known to the compiler at runtime. It is mostly caused by the program written by the programmer.

    Example Exception

    Java

    class GFG {

        public static void main(String[] args)

        {

            int a = 5, b = 0;

            try {

                int c = a / b;

            }

            catch (ArithmeticException e) {

                e.printStackTrace();

            }

        }

    }

    Output: 

    Finally now wrapping-off the article by plotting the differences out between them in a tabular format as provided below as follows:

    Errors Exceptions
    Recovering from Error is not possible. We can recover from exceptions by either using try-catch block or throwing exceptions back to the caller.
    All errors in java are unchecked type. Exceptions include both checked as well as unchecked type.
    Errors are mostly caused by the environment in which program is running. Program itself is responsible for causing exceptions.

    Errors can occur at compile time as well as run time. Compile Time: eg Syntax Error

    Run Time: Logical Error.

    All exceptions occurs at runtime but checked exceptions are known to the compiler while unchecked are not.
    They are defined in java.lang.Error package. They are defined in java.lang.Exception package
    Examples : java.lang.StackOverflowError, java.lang.OutOfMemoryError Examples : Checked Exceptions : SQLException, IOException Unchecked Exceptions : ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException.

    Понравилась статья? Поделить с друзьями:
  • Die lage von meine traumwohnung ganz wichtig fur mich ist исправить ошибки
  • Did you get an error message перевод
  • Did not successfully update the mbr continuing как исправить
  • Did not match any file s known to git ошибка
  • Did not connect potential security issue как исправить