JAVA-Notes-Unit-2_Part 3
JAVA-Notes-Unit-2_Part 3
In Java, exceptions are categorized into two main types: checked exceptions and
unchecked exceptions. Additionally, there is a third category known as errors. Let's
delve into each of these types:
1. Checked Exception
2. Unchecked Exception
3. Error
3. Errors
Errors represent exceptional conditions that are not expected to be caught under
normal circumstances.
They are typically caused by issues outside the control of the application, such
as system failures or resource exhaustion. Errors are not meant to be caught or handled
by application code.
Built-in exceptions are part of the Java standard library and provide a
standardized way to handle common exceptional scenarios.
1. Checked Exceptions
2. Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time. In simple words, if a
program throws an unchecked exception, and even if we didn’t handle or declare it,
the program would not give a compilation error. Examples of Unchecked Exception
are listed below:
package vehicle;
else
{
isRunning = true;
System.out.println(brand + " engine started.");
}
}
// Method to stop the vehicle engine
public void stopEngine()
{
if (!isRunning)
{
throw new IllegalStateException("The vehicle engine is not running.");
}
isRunning = false;
System.out.println(brand + " engine stopped.");
}
// Method to refuel the vehicle
public void refuel(int amount)
{
if (amount <= 0)
{
throw new IllegalArgumentException("Refuel amount must be positive.");
}
fuelLevel += amount;
if (fuelLevel > 100)
{
fuelLevel = 100; // Fuel level cannot exceed 100%
}
System.out.println(brand + " refueled. Current fuel level: " + fuelLevel + "%");
}
// Method to drive the vehicle
public void drive()
{
if (!isRunning)
{
throw new IllegalStateException("The vehicle is not running. Start the engine first.");
}
System.out.println(brand + " is driving.");
}
}
//Main.java
import vehicle.Vehicle;
public class Main
{
public static void main(String[] args)
{
try
{
// Create a new vehicle with a valid fuel level
Vehicle v1 = new Vehicle("Toyota", 50);
Output:
1. try block
A try block consists of all the doubtful statements that can throw exceptions.
A try block cannot be executed on itself; it requires at least one catch block
or finally block.
If an exception occurs, the control flows from the try-to-catch block.
When an exception occurs in a try block, the appropriate exception object is
redirected to the catch block. This catch block handles the exception
according to its statements and continues the execution.
Syntax
try
{
//Doubtful Statements.
}
2. catch block
The catch block handles the exception raised in the try block.
The catch block or blocks follow every try block.
The catch block catches the thrown exception as its parameter and executes
the statements inside it.
The declared exception must be the parent class exception, the generated
exception type in the exception class hierarchy, or a user-defined
exception.
Syntax
try
{
//Doubtful Statements.
}
catch(Exception e)
{
// code to handle exceptions
}
We can use multiple catch statements for different kinds of exceptions that can
occur from a single block of code in the try block.
Syntax
try
{
// code to check exceptions
}
catch (exception1)
{
// code to handle the exception
}
catch (exception2)
{
// code to handle the exception
}
3. finally block
The finally block in Java always executes even if there are no exceptions. This
is an optional block. It is used to execute important statements such as closing
statements, releasing resources, and releasing memory. There could be one final block
for every try block. This finally block executes after the try...catch block.
Syntax
try
{
//code
}
catch (ExceptionType1 e1)
{
// catch block
}
finally
{
// finally block always executes
}
4. throw Keyword
Syntax
5. throws keyword
The throws keyword is used in the method signature to indicate that a method
in Java can throw particular exceptions. This notifies the method that it must manage
or propagate these exceptions to the caller.
Syntax
Here's an example of how each of these can be used in the context of a Vehicle class.
class Vehicle
{
private boolean isRunning = false;
private int fuelLevel = 10; // Fuel level out of 100
// Method to start the vehicle
public void start()
{
System.out.println("Vehicle is starting...");
isRunning = true;
}
// Method to stop the vehicle
public void stop()
{
if (!isRunning)
{
// Throw a custom unchecked exception if trying to stop an already stopped vehicle
throw new VehicleAlreadyStoppedException("Vehicle is already stopped.");
}
System.out.println("Vehicle is stopping...");
isRunning = false;
}
// Method to accelerate the vehicle
public void accelerate(int speed)
{
try
{
if (speed < 0)
{
throw new IllegalArgumentException("Speed cannot be negative.");
}
System.out.println("Accelerating to " + speed + " km/h...");
}
catch (IllegalArgumentException e)
{
System.out.println("Error while accelerating: " + e.getMessage());
}
finally
{
System.out.println("Acceleration attempt completed.");
}
}
catch (VehicleAlreadyStoppedException e)
{
System.out.println("Caught exception in stop method: " + e.getMessage());
}
Syntax
Syntax
Statements
You just need to extend the predefined RuntimeException class to create your own
Exception.
class Vehicle
{
private boolean isRunning = true;
private int fuelLevel = 10; // Fuel level out of 100
catch (OutOfFuelException e)
{
System.out.println("Caught exception in drive method: " + e.getMessage());
}
}
}