Introduction

In this article, we discuss the differences between exceptions and errors in Java. Both errors and exceptions are derived from "java.lang.Throwable" in Java.

Difference between exception and error in Java

Error in Java

When a dynamic linking failure or other hard failures in the Java Virtual Machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.
A few examples causing Java Runtime Errors are:
  1. Using a negative size in an array.
  2. Conversion of a string into a number.
  3. Divide an integer by zero.
  4. Access an element that is out of bounds of an array
  5. Store a value that is of incompatible data type in an array.
  6. Cast an instance of base class to one of its derived classes.
  7. Using a null object to reference an object's member.
  8. Capitalization of keywords.
  9. Missing brackets in a no-argument message.
  10. Writing the wrong format for a class method, etcetera.
Example
In this example, we show different errors.
  1. class MyErrorClass {
  2. void fun1() {
  3. int y = 102;
  4. // Error, closing brace is missing
  5. void fun2() {
  6. int x = 1220;
  7. }
  8. }
  9. }
Output
Fig-1.jpg

Exception in Java

An exception is called and even occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
When an exception occurs within a method, the method creates an object and hands it off to the runtime system. Creating an exception object and handing it to the runtime system is called throwing an exception.
It can occur for any of the following reasons:

Exception types in Java

Exceptions are divided mainly into the following three types:
  1. Checked
  2. Runtime/unchecked
  3. Error
Let's take some exception
1. ArithmeticException
If we divide by zero, there occurs an ArithmeticException.
int x=12230/0;//ArithmeticException
2. NullPointException
If we provide a null value in any variable and performing some task, that causes an NullPointException.
String str=null;

System.out.println(str.length()); //NullPointException
3. NumberFormatException
The wrong/different formatting of any value, may cause a NumberFormatException.
String str="xyz";

int x=Integer.parseInt(str); //NumberFormatException
4. ArrayIndexOutOfBoundsException
If we use a value that is an incorrect index then that causes an ArrayIndexOutOfBoundsException.
int x[]=new int[5];

x[10]=1223; //ArrayIndexOutOfBoundException
Example
In this example, we saw an ArithmeticException and use try-catch to handle this exception.
  1. class ExceptionEx
  2. {
  3. public static void main(String[] args)
  4. {
  5. try
  6. {
  7. int result = 1243443 / 0;
  8. } catch (ArithmeticException ae)
  9. {
  10. System.out.println(ae);
  11. }
  12. System.out.println("rest code");
  13. }
  14. }
Output
Fig-2.jpg