Error and exception in java

Exceptions:

Exception in java, represents an exceptional event. It is an event that disrupts the program’s normal flow, during program execution. We can handle exceptions by using try-catch or throws keywords. Exceptions are divided into following two categories:  checked exceptions and unchecked exceptions.

e.g. – NullPointerException, ArithmeticException, IOException, SQLException etc.

Note: Exceptions generally occur because of the code of our program.

Example: Exception

public class Main { 
 
	public static void main(String[] args) 
	{ 
		int num1 = 10, num2 = 0; 
 
		// Try to divide by zero 
		try { 
			int result = num1 / num2; 
		} 
		catch (ArithmeticException e) { 
			e.printStackTrace(); 
		} 
	} 
}

Output

java.lang.ArithmeticException: / by zero                         
        at Main.main(Main.java:9)

Error:

Errors represents the exceptional conditions that are not checked by compiler at the compile time, they are checked at runtime. An error will not force you to use try-catch or throws keywords to handle it. Error and their subclasses are used to represent errors. Errors are irrecoverable and can’t be avoided by programmer. That means, it surely terminate the program abnormally.

e.g. – StackOverFlow, OutOfMemoryError etc.

Note: Errors generally occur because of the lack of the system resources. Errors represents the unchecked types. 

Example: Error

class StackOverflow { 
    public static void testError(int num) 
    { 
        if (num == 0) 
            return; 
        else { 
            testError(num++); 
        } 
    } 
} 
public class Main { 
 
    public static void main(String[] args) 
    { 
        StackOverflow.testError(1); 
    } 
}

Output

Exception in thread "main" java.lang.StackOverflowError
	at StackOverflow.testError(Main.java:7)

Note: Even if we handle errors using try-catch blocks, application will not recover if errors happened.

 

Difference between ERRORS and EXCEPTIONS in Java

ERROR EXCEPTION
It can be caused due to lack of system resources. It can be caused due to bad code.
It represents an irrecoverable event. It represents a recoverable event.
Errors cannot be handled by program code. Errors cannot be handled by program code (using try, catch, and throw keywords).
In case of error program will terminate abnormally. In case of exception, we can handle it by using try, catch or throws keyword and hence can control the abnormal termination of program.
Errors are of unchecked type. Exceptions can be of checked or unchecked type.
Errors defined in java.lang.Error package. Exceptions defined in java.lang.Exception.
Examples:

OutOfMemory, StackOverFlow.

Examples:

Checked Exceptions : NoSuchMethod, ClassNotFound.
Unchecked Exceptions : NullPointer, IndexOutOfBounds.

 

Java interview questions on Exception Handling