- There will be breakage while executing the code, eg if. tried divide by zero etc. such sort of condition need to be taken care in code. these conditions throws exception or error. This exceptions need to be handled in code for smooth flow.
- The
java.lang.Exception
class is the root of the exception hierarchy in Java. - Throwable is the superclass for Exception and Error.
- Exception is the superclass for checked & unchecked exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Throwable | +-- Exception (checked) | | | +-- IOException | | | +-- SQLException | | | +-- ... | +-- Error (unchecked) | +-- OutOfMemoryError | +-- StackOverflowError | +-- ... |
There are two main types of exceptions in Java: checked exceptions and unchecked exceptions.
- Checked exceptions: These are exceptions that must be caught and handled by the code, otherwise, the code will not compile. Examples of checked exceptions include
IOException
,SQLException
, andFileNotFoundException
. These exceptions are generally checked exceptions. - Unchecked exceptions: These are exceptions that do not need to be caught or handled. Examples of unchecked exceptions include
NullPointerException
,IndexOutOfBoundsException
, andIllegalArgumentException
.
Java code for Checked & Unchecked Exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class Car { private int speed; public Car(int speed) { this.speed = speed; } public int getSpeed() { return speed; } public void setSpeed(int speed) throws SpeedOutOfRangeException { if (speed < 0 || speed > 150) { throw new SpeedOutOfRangeException("Speed must be between 0 and 150"); } this.speed = speed; } } class SpeedOutOfRangeException extends Exception { public SpeedOutOfRangeException(String message) { super(message); } } public class CarExceptionExample { public static void main(String[] args) { try { Car car = new Car(200); } catch (SpeedOutOfRangeException e) { System.out.println("Caught checked exception: " + e.getMessage()); } Car car = new Car(50); car.setSpeed(-10); } } |
In this example, we have a Car
class with a method setSpeed
that sets the speed of the car. The method throws a SpeedOutOfRangeException
if the specified speed is not within the allowed range of 0 to 150.
In the main
method, we create a car object with speed 200, which is out of range and will result in a SpeedOutOfRangeException
being thrown. We catch this exception and print an error message.
Exception Handling: using try-catch
To handle exceptions in the code, you need to wrap the code that might throw an exception within a try
block and catch the exception in a catch
block. The code within the try
block is executed until an exception is thrown. If an exception is thrown, the control is transferred to the catch
block that matches the type of exception thrown.
Here’s an updated example of the code with exception handling:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
class Car { private int speed; public Car(int speed) { this.speed = speed; } public int getSpeed() { return speed; } public void setSpeed(int speed) throws SpeedOutOfRangeException { if (speed < 0 || speed > 150) { throw new SpeedOutOfRangeException("Speed must be between 0 and 150"); } this.speed = speed; } } class SpeedOutOfRangeException extends Exception { public SpeedOutOfRangeException(String message) { super(message); } } public class CarExceptionExample { public static void main(String[] args) { try { Car car = new Car(200); car.setSpeed(200); } catch (SpeedOutOfRangeException e) { System.out.println("Caught checked exception: " + e.getMessage()); } try { Car car = new Car(50); car.setSpeed(-10); } catch (SpeedOutOfRangeException e) { System.out.println("Caught checked exception: " + e.getMessage()); } } } |
In this example, we have added a try
–catch
block around each instance of creating and setting the speed of a car. If an exception is thrown, it will be caught and the error message will be printed.
Understanding try-catch-finally:
The try-catch-finally
combination in Java is used to handle exceptions that may occur in a program.
Here’s how the try-catch-finally
combination works:
- The code that might throw an exception is placed inside a
try
block. - If an exception is thrown, the code inside the corresponding
catch
block will be executed. Thecatch
block is used to handle the exception and can include code to recover from the exception or to log the error. - The
finally
block is optional and contains code that will be executed regardless of whether an exception was thrown or not. It is typically used to release resources or to clean up after thetry
block has completed.
Here’s an example of how the try-catch-finally
combination can be used in a program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
class Car { private int speed; public Car(int speed) { this.speed = speed; } public int getSpeed() { return speed; } public void setSpeed(int speed) throws SpeedOutOfRangeException { if (speed < 0 || speed > 150) { throw new SpeedOutOfRangeException("Speed must be between 0 and 150"); } this.speed = speed; } } class SpeedOutOfRangeException extends Exception { public SpeedOutOfRangeException(String message) { super(message); } } public class CarExceptionExample { public static void main(String[] args) { Car car = new Car(100); try { car.setSpeed(200); } catch (SpeedOutOfRangeException e) { System.out.println("Caught SpeedOutOfRangeException: " + e.getMessage()); } finally { System.out.println("Finally block executed"); } } } |
In this example, the code inside the try
block tries to set the speed of the car to 200, which is outside the allowed range of 0 to 150. As a result, a SpeedOutOfRangeException
is thrown and caught by the catch
block, which prints an error message. Finally, the code inside the finally
block is executed, which prints a message indicating that it has been executed.