Java Errors
Java Errors
Java errors are mistakes in a program that stop it from working properly or make it give wrong results. Even experienced developers can make these mistakes. The important thing is to learn how to find (spot) and fix them (debugging). These errors help us understand what is going wrong in the program and how to correct it.
Java errors are mistakes in code that stop the program or produce wrong output, and we fix them by debugging.
Types of Errors
1. Syntax Errors
These errors happen when you break the rules of Java language (grammar mistakes).
Β Example:
- Missing semicolon ;
2. Runtime Errors
These errors happen while the program is running.
Β Example:
- Dividing a number by zero
3.Logical Errors
These errors happen when the program runs fine but gives wrong output due to wrong logic.
Example:
- Wrong calculation formula
Β
Β
Java Exceptions
A Java exception is an unexpected problem or event that occurs during the execution of a program, which can disturb the normal flow of the program. When an exception happens, the program may stop or give incorrect results if it is not handled properly.
Β
Exception Handling (try and catch)
Exception handling in Java is a way to catch and handle errors that occur during runtime, so the program does not crash suddenly. It helps the program continue running smoothly even when an error happens.
Java uses try and catch blocks to handle exceptions.
1.try Statement
The try block is used to write code that may cause an error. It is tested while the program is running.
2.catch Statement
The catch block is used to handle the error if it occurs in the try block. It defines what should happen when an exception is found.
Example
public class Main {
Β public static void main(String[] args) {
Β Β try {
Β Β Β // Creating an array with 3 elements (index: 0, 1, 2)
Β Β Β int[] myNumbers = {1, 2, 3};
Β Β Β // Trying to access index 10 (which does NOT exist)
Β Β Β // This will cause an error (ArrayIndexOutOfBoundsException)
Β Β Β System.out.println(myNumbers[10]);
Β Β } catch (Exception e) {
Β Β Β // This block runs when an error occurs in try block
Β Β Β // Printing simple error message
Β Β Β System.out.println("Something went wrong.");
Β Β }
Β }
}