Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Overview of Errors and Exceptions in Java

[post-views]

 

 

In this lesson, you will learn

  • Understanding Errors
    • Compile Time Errors
    • Run Time Errors
  • Understanding Exceptions

 

Understanding Errors

Errors are mistakes or faults that can make a program go wrong and may terminate the program execution abruptly.

In Java, the errors can generally be classified into two main categories: compile-time errors and run-time errors.

 

 

Compile-Time Errors

Compile-time errors occur during the compilation phase of your program before the Java Virtual Machine (JVM) begins execution.

Compile-time errors typically include syntax errors, type-checking errors, and any other errors that can be detected during the compilation of the program.

 

The following are the common compile time errors.

 

 

Examples of Compile-Time Errors

 

1. Syntax errors: Mistakes in the code that violate the grammar rules of the Java language.

public class CompileTimeExample {
    public static void main(String[] args) {
        System.out.println("Hello, world!") // Missing semicolon
    }
}

 

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Syntax error, insert ";" to complete BlockStatements

	at stringdemo.CompileTimeExample.main(CompileTimeExample.java:6)

 

2. Type-checking errors: Attempting to operate on a data type that is not allowed.

public class CompileTimeExample {
    public static void main(String[] args) {
        int number = "123"; 
        // Trying to assign a String to an integer variable
    }
}

 

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from String to int

	at stringdemo.CompileTimeExample.main(CompileTimeExample.java:6)

 

3. Undeclared variable: Trying to use a variable that has not been declared.

public class CompileTimeExample {
    public static void main(String[] args) {
        x = 100; // x is not declared
    }
}

 

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	x cannot be resolved to a variable

	at stringdemo.CompileTimeExample.main(CompileTimeExample.java:6)

 

Run-Time Errors

Run-time errors occur during the program execution after the program is successfully compiled.

Run-time errors produce wrong results due to the wrong logic and abruptly terminate the flow of the program.

 

Note: These errors are usually more difficult to debug since they often depend on the program’s input or the current state of the program.

 

The following are the common runtime errors.

 

 

Examples of Run-time Errors

 

1. Division by zero: Attempting to divide a number by zero.

public class RunTimeExample {
    public static void main(String[] args) {
        int result = 10 / 0; // ArithmeticException is thrown
    }
}

 

2. Accessing an out-of-bounds element in an array: Trying to access an array element with an invalid index.

public class RunTimeExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        System.out.println(numbers[3]); // ArrayIndexOutOfBoundsException
    }
}

 

Exceptions

  • An exception is an unnatural condition that arises in a code at run time.
  • An exception is an abnormal event or condition that disrupts the normal flow of the program’s instructions during its execution.
  • Exceptions are used for signaling errors, resource issues, and other exceptional conditions, allowing developers to manage them gracefully instead of crashing the application.

 

Example: Common Standard Java Exceptions or Run-time Errors

 

1. ArithmeticException

  • Thrown when an exceptional arithmetic condition occurs, such as dividing by zero.

 

int result = 10 / 0; // Throws ArithmeticException

 

2. NullPointerException

  • Occurs when an application attempts to use null in a case where an object is required.

 

String text = null;
int length = text.length(); // Throws NullPointerException

 

3. ArrayIndexOutOfBoundsException

  • Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

 

int[] numbers = new int[5];
int number = numbers[5]; // Throws ArrayIndexOutOfBoundsException

 

ClassCastException

  • Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

 

Object x = new Integer(0);
System.out.println((String)x); // Throws ClassCastException

 

IndexOutOfBoundsException

  • Thrown by methods that have checked that an index is out of range. ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException are more specific instances of IndexOutOfBoundsException.

 

String str = "hello";
char ch = str.charAt(5); // Throws IndexOutOfBoundsException

 

IllegalArgumentException

  • Thrown to indicate that a method has been passed an illegal or inappropriate argument.

 

Thread t = new Thread();
t.setPriority(11); // Throws IllegalArgumentException

 

IllegalStateException

  • Thrown to indicate that a method has been invoked at an illegal or inappropriate time.

 

Iterator<String> it = Arrays.asList("a", "b").iterator();
it.remove(); // Throws IllegalStateException

 

NoSuchElementException

  • Thrown by various accessor methods to indicate that the element being requested does not exist.

 

Iterator<String> it = Arrays.asList().iterator();
it.next(); // Throws NoSuchElementException

 

NumberFormatException

  • Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

 

int num = Integer.parseInt("abc"); // Throws NumberFormatException

 

StackOverflowError

  • Occurs when a stack overflow occurs because an application recurses too deeply.

 

public void recursivePrint(int num) {
    System.out.println("Number: " + num);
    recursivePrint(++num);
}

 

In the next lesson, you will learn how to handle exceptins raised in the program using the try-catch block.

 

 


 

End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review