Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding throw Keyword in Java

 

In this lesson, you will learn

  • Understanding ‘throw’ Keyword

 

Understanding The ‘throw’ Keyword

So far, you have only been catching exceptions thrown by the Java run-time system. However, your program can throw an exception explicitly, using the throw statement also.

  • The keyword ‘throw' is used to explicitly throw an exception from a method or block of code.

 

Syntax

throw ThrowableInsatnce;

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

 

Note: Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions

 

Examples

throw new Exception("An error occurred");
throw new ArithmeticException();
throws new NumberFormatException();

 

The following code throw an exception explicitly from a checkAge() method.

void checkAge() {
     throw new Exception("An error occurred");
     //Statements..
}

 

Working Process of the ‘throw’ Keyword

The execution flow stops immediately after the throw statement, and any subsequent statements are not executed.

The nearest enclosing try block is inspected to see if it has a catch statement matching the exception type. If a match is found then the control is transferred to that statement else then the next enclosing try statement is inspected, and so on.

If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

Consider the following code snippets that is explaining the use of the 'throw' statement and throw an ArithmeticException.

Example

package l6;

public class ThrowExample {
    static void checkAge(int age) {
		 if (age < 18) {
	            // Throw an ArithmeticException if the age is less than 18
	            throw new ArithmeticException("Access denied - "
	            		+ "You must be at least 18 years old.");
	        } else {
	            System.out.println("Access granted - You are old enough!");
	        }
    }
    public static void main(String[] args) { 
    	checkAge(15); // This will throw an ArithmeticException        
    }
}

 

Output

Exception in thread "main" java.lang.ArithmeticException: 
Access denied - You must be at least 18 years old.
	at l6.ThrowExample.checkAge(ThrowExample.java:7)
	at l6.ThrowExample.main(ThrowExample.java:15)

 

Note: An exception can be handled either in the method that raises the exception or in the calling method.

The following code, the throw new ArithmeticException() is used to throw a ArithmeticException object and the calling the method i.e. main() handled the exception raised in the checkAge() method.

 

Example 1: The ‘throw’ Statement: Handle Execption in Calling Function

package l6;

public class ThrowExample {
    static void checkAge(int age) {
		 if (age < 18) {
	            // Throw an ArithmeticException if the age is less than 18
	            throw new ArithmeticException("Access denied - "
	            		+ "You must be at least 18 years old.");
	        } else {
	            System.out.println("Access granted - You are old enough!");
	        }
    }
    
    public static void main(String[] args) { 
    	try {
    		checkAge(15); // This will throw an ArithmeticException
		} catch (ArithmeticException e) {
			System.out.println("Exception caught in main: "+e);
		}
        
    }
}

Output

Exception caught in main: java.lang.ArithmeticException: 
Access denied - You must be at least 18 years old.

 

You can handle the exception in the method itself that raised the exception as shown in the following code snippet

Example – Handle the Exception in the Method Itself

package l6;

public class ThrowExample2 {
    static void checkAge(int age) {
    	try {
    		if (age < 18) {
    			// Throw an ArithmeticException if the age is less than 18
    			throw new ArithmeticException("Access denied - "
    	            		+ "You must be at least 18 years old.");
    	    } 
    		else {
    			System.out.println("Access granted - You are old enough!");
    	    }
		} catch (ArithmeticException e) {
			System.out.println("Exception caught in main: "+e);
		}
    }
    
    public static void main(String[] args) { 
    	checkAge(15); // This will throw an ArithmeticException        
    }
}

Output

Exception caught in main: java.lang.ArithmeticException: 
Access denied - You must be at least 18 years old.

 

Rethrowing an Exception

  • Rethrowing an exception means catching an exception in a catch block and then throwing it again.
  • This can be useful if you want to perform some action when an exception occurs (like logging) but then want to allow a higher level of the program to handle the exception. Here’s an example:

 

Example: Rethrowing an Exception

package l6;

public class RethrowingExceptionEx1 {
	static void checkAge(int age) {
    	try {
    		if (age < 18) {
    			// Throw an ArithmeticException if the age is less than 18
    			throw new ArithmeticException("Access denied - "
    	            		+ "You must be at least 18 years old.");
    	    } 
    		else {
    			System.out.println("Access granted - You are old enough!");
    	    }
		} catch (ArithmeticException e) {
			System.out.println("Exception caught in Method: "+e);
            // Rethrowing an exception
			throw e;
		}
    }

	public static void main(String[] args) {
		try {
			checkAge(15); // This will throw an ArithmeticException   
		} catch (Exception e) {
			System.out.println("Exception caught in main");
		}
	}
}

Output

Exception caught in Method: java.lang.ArithmeticException: 
Access denied - You must be at least 18 years old.
Exception caught in main

 

 

 


 

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