Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information


to the programmer that there may occur an exception. So, it is better for the
programmer to provide the exception handling code so that the normal flow of the
program can be maintained.

Syntax of Java throws

return_type method_name() throws exception_class_name{


//method code
}
• Imagine you're writing a
program to welcome people
to an amusement park ride
that only allows people who
are at least 18 years old. If
someone under 18 tries to
get on the ride, you want to
stop them and let them
know they're too young.
public class AmusementParkRide {
public static void main(String[] args) {
int age = 16; // The age of the person trying to get on the ride
try {
// Let's check if the person is old enough
checkAge(age);
System.out.println("Welcome to the ride. Have fun!");
} catch (Exception e) {
// If they're not old enough, stop them and print a message
System.out.println("Sorry, you're not old enough. " + e.getMessage());
}
}
// This method will throw an exception if the age is under 18
static void checkAge(int age) throws Exception {
if (age < 18) {
// This line throws a new Exception with a message
throw new Exception("You must be at least 18 years old.");
}}}
import java.io.IOException;
class DeviceOperation {
void initiateOperation() throws IOException {
throw new IOException("device error"); // Checked exception
}
void performOperation() throws IOException {
initiateOperation(); Output:
}
void executeDeviceTask() { exception handled
try {
performOperation(); normal flow...
} catch (Exception e) {
System.out.println("Exception handled"); } }
public static void main(String args[]) {
DeviceOperation device = new DeviceOperation();
device.executeDeviceTask();
System.out.println("Normal flow..."); } }
Sr. no. Basis of Differences throw throws
1. Definition Java throw keyword is used throw an Java throws keyword is
exception explicitly in the code, used in the method
inside the function or the block of signature to declare an
code. exception which might be
thrown by the function
while the execution of the
code.
2. Type of exception Using throw Using throws keyword, we can
keyword, we can only propagate declare both checked and unchecked
unchecked exception i.e., the exceptions. However, the throws
checked exception cannot be keyword can be used to propagate
propagated using throw only. checked exceptions only.
3. Syntax The throw keyword is followed by an The throws keyword is
instance of Exception to be thrown. followed by class names of
Exceptions to be thrown.
4. Declaration throw is used within the method. throws is used with the
method signature.
5. Internal implementation We are allowed to throw only one We can declare multiple
exception at a time i.e. we cannot exceptions using throws
throw multiple exceptions. keyword that can be
thrown by the method. For
Java finally block
Java finally block is a block used to execute important code
such as closing the connection, etc.

Java finally block is always executed whether an exception is


handled or not. Therefore, it contains all the necessary
statements that need to be printed regardless of the exception
occurs or not.

The finally block follows the try-catch block.


Flowchart of
finally block
Why use Java finally block?
finally block in Java can be used to put "cleanup" code such as closing a file, closing connection, etc.
The important statements to be printed can be placed in the finally block

When an exception does not occur

TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed"); }
System.out.println("rest of the code..."); } }
When an exception occurr but not handled by the catch block

public class TestFinallyBlock1{


public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data); }
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e); }
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed"); }
System.out.println("rest of the code...");
} }
When an exception occurs and is handled by the catch block

public class TestFinallyBlock2{


public static void main(String args[]){
try {
System.out.println("Inside try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
System.out.println("Exception handled");
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
USER DEFINED EXCEPTION
❑ We can create our exceptions in java
❑ User defined exceptions should extend the exception class
❑ Creating our own Exception is known as custom exception or user-defined
exception.

1.public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5.}
User-Defined Exceptions :

Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, the user can also create exceptions which are called ‘user-
defined Exceptions’.

The following steps are followed for the creation of a user-defined Exception.

The user should create an exception class as a subclass of the Exception class. Since
all the exceptions are subclasses of the Exception class, the user should also make
his class a subclass of it. This is done as:

class MyException extends Exception


We can write a default constructor in his own exception class.

MyException(){}

We can also create a parameterized constructor with a string as a parameter.


We can use this to store exception details. We can call the superclass(Exception)
constructor from this and send the string there.

MyException(String str)
{
super(str);
}

To raise an exception of a user-defined type, we need to create an object to his


exception class and throw it using the throw clause, as:

MyException me = new MyException(“Exception details”);


throw me;
// Define the custom exception class

class MinorAgeException extends Exception {


public MinorAgeException() {
super("Age must be 18 or above to proceed."); // Hard-coded message
}
}
// Class that uses the custom exception
public class Application
{
// Method to check the age
public static void checkAge(int age) throws MinorAgeException {
if (age < 18) {
throw new MinorAgeException();
} else {
System.out.println("You are eligible.");
} }
public static void main(String[] args) {
try {
checkAge(16);
} catch (MinorAgeException e) {
System.out.println("Exception: " + e.getMessage());
}}}
Throwing User-defined Exception
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str) {
// Calling constructor of parent Exception
super(str); } }
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[]) {
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
} } }

You might also like