Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Understanding the throws Keyword in Java1

 

In this lesson, you will learn

  • The ‘throws’ Keyword
  • Examples

 

Background

Suppose a method is capable of causing an exception that it does not handle. In that case, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration.

 

What is a ‘throws’ Keyword?

  • The throws keyword is used in the signature of a method to indicate that this method might throw one or more exceptions during its execution.
  • These exceptions must be handled by the method that calls this method, either by using a try-catch block or by declaring the exception in its own throws clause.

 

Syntax

type method-name(parameter-list) throws exception-list
{
    // body of method
}

 

Here, an exception list is a comma-separated list of the exceptions that a method can throw

 

Example

The following example is incorrect because the program does not specify a throws clause to declare the fact and it tries to throw an exception (Checked type) that it does not catch.

The following program would not compile.

 

package throwskeyword;

public class ThrowsExample {
	
	public static void executeProcess() {
		System.out.println("Inside a method executeprocess()..");
		throw new IllegalAccessException("Access Resources");
	}

	public static void main(String[] args) {
		executeProcess();
        System.out.println("Inside a main() method..");
	}
}

Output

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem: 
	Unhandled exception type IllegalAccessException

	at throwskeyword.ThrowsExample1.executeProcess(ThrowsExample1.java:7)
	at throwskeyword.ThrowsExample1.main(ThrowsExample1.java:11)

 

How to Solve The Above Compilation Error?

 

Method – 1:

To make this example compile, you need to make two changes. First, you need to declare that executeProcess() throws IllegalAccessException. Second, main( ) must define a try/catch statement that catches this exception.

package throwskeyword;

public class ThrowsExample1 {
	
	public static void executeProcess() throws IllegalAccessException {
		System.out.println("Inside a method executeprocess()..");
		throw new IllegalAccessException("Access Resources");
	}

	public static void main(String[] args) {
		try {
			executeProcess();
		} catch (IllegalAccessException e) {
			System.out.println("Exception Caught: "+e);
		}
        System.out.println("Inside a main() method..");
	}
}

Output

Inside a method executeprocess()..
Exception Caught: java.lang.IllegalAccessException: Access Resources
Inside a main() method..

 

Method -2:

You can handle the exception using a try/catch block in the method itself.

 

package throwskeyword;

public class ThrowsExample2 {
	
	public static void executeProcess() {
		try {
			System.out.println("Inside a method executeprocess()..");
			throw new IllegalAccessException("Access Resources");
		} catch (Exception e) {
			System.out.println("Exception Caught: "+e);
		}
	}
	
	public static void main(String[] args) {
		executeProcess();
		System.out.println("Inside a main() method..");
	}
}

Output

Inside a method executeprocess()..
Exception Caught: java.lang.IllegalAccessException: Access Resources
Inside a main() method..

 

Example 2: Using ‘throws’

package throwskeyword;

public class AccessExample {

    private void restrictedMethod() {
        System.out.println("This method is restricted "
        		+ "and should not be accessed.");
    }

    public void accessCheck(boolean access) throws IllegalAccessException {
        if (!access) {
            // Explicitly throw an IllegalAccessException with a message
            throw new IllegalAccessException("Access to "
            		+ "restrictedMethod is denied.");
        } else {
            // If access is allowed, invoke the method
            restrictedMethod();
            System.out.println("Access granted to restrictedMethod.");
        }
    }

    public static void main(String[] args) {
        AccessExample example = new AccessExample();
        try {
            // Attempt to access the restricted method
            example.accessCheck(false);
        } catch (IllegalAccessException e) {
            System.err.println("Exception caught: " + e.getMessage());
        }
    }
}

 

Output

Test Case -1: When example.accessCheck(false);

Exception caught: Access to restrictedMethod is denied.

 

Test Case -2: When example.accessCheck(true);

This method is restricted and should not be accessed.
Access granted to restrictedMethod.

 

Explanation

In this example, the accessCheck method takes a boolean parameter access to determine whether to allow access to a restricted method (restrictedMethod). If access is false, it throws an IllegalAccessException indicating that access is denied. The main method tries to call accessCheck with false, simulating an unauthorized access attempt, which leads to catching and handling the IllegalAccessException.

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

5.0
5.0 out of 5 stars (based on 1 review)
Excellent100%
Very good0%
Average0%
Poor0%
Terrible0%

 

 

19/04/2025

good

 

 

Submit a Review