throws in java

In Java, the throw keyword is used to explicitly throw an exception. Exceptions are a way to handle errors and exceptional conditions in Java programs. Here’s a basic overview of how it works:

  1. Throwing an Exception:
  • The throw statement is followed by an instance of an exception.
  • This instance can be a built-in exception or a custom exception that extends the Exception class or one of its subclasses.
   throw new SomeException("This is an example exception");
  1. Catching the Exception:
  • When an exception is thrown, it can be caught and handled using a try-catch block.
  • The catch block specifies the type of exception it can handle.
   try {
       // code that may throw an exception
   } catch (SomeException e) {
       // code to handle the exception
   }

Here’s an example that demonstrates the use of throw and try-catch:

   class CustomException extends Exception {
       public CustomException(String message) {
           super(message);
       }
   }

   public class Example {
       public static void main(String[] args) {
           try {
               // Some condition that triggers an exception
               if (someCondition) {
                   throw new CustomException("Custom exception occurred");
               }

               // Rest of the code
           } catch (CustomException e) {
               System.err.println("Caught an exception: " + e.getMessage());
               // Handle the exception or take appropriate action
           }
       }

In this example, if the someCondition is true, a CustomException is thrown. The catch block then handles this exception and executes the code within the catch block.

In Java, the throws keyword is used in the method declaration to indicate that the method may throw certain types of exceptions. It is part of the method signature and is followed by a list of exception types separated by commas.

Syntax:

returnType methodName(parameters) throws ExceptionType1, ExceptionType2, ... {
    // Method implementation
}

Example:

public void readFile(String fileName) throws FileNotFoundException, IOException {
    // Code that may throw FileNotFoundException or IOException
}

In this example, the readFile method is declared to potentially throw two types of exceptions: FileNotFoundException and IOException. This alerts the caller that they should handle or propagate these exceptions when calling the method.

Key Points:

  1. Declaring Exceptions:
  • The throws clause is used to declare exceptions that a method may throw. It is part of the method signature.
  1. Checked Exceptions:
  • Typically, the throws clause is used for checked exceptions, which are exceptions that must be either caught or declared.
  1. Propagation of Exceptions:
  • When a method declares that it throws certain exceptions, any caller of that method must either catch those exceptions or declare that it also throws them.
  1. Unchecked Exceptions:
  • Unchecked exceptions (runtime exceptions) are not required to be declared using throws. However, they can still be declared if the developer wishes to make it explicit.

Example with Checked Exception:

public class FileReader {
    public String readContent(String fileName) throws FileNotFoundException, IOException {
        try (FileReader fileReader = new FileReader(fileName);
             BufferedReader bufferedReader = new BufferedReader(fileReader)) {

            // Code to read and process the file content
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line).append("\n");
            }

            return content.toString();
        }
    }
}

In this example, the readContent method reads the content of a file. It declares that it may throw two checked exceptions: FileNotFoundException and IOException. The caller of this method must handle or declare these exceptions.

Example with Unchecked Exception:

public class Calculator {
    public int divide(int dividend, int divisor) throws ArithmeticException {
        if (divisor == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return dividend / divisor;
    }
}

In this example, the divide method declares that it may throw an ArithmeticException if an attempt is made to divide by zero. Since ArithmeticException is an unchecked exception, the throws clause is optional, but it’s included for clarity.

Best Practices:

  1. Be Specific:
  • Declare specific exceptions rather than using a generic throws Exception unless there’s a compelling reason to do otherwise.
  1. Document Exceptions:
  • Document the exceptions that a method may throw using comments or documentation to guide developers who use the method.
  1. Checked vs. Unchecked:
  • Use throws for checked exceptions that are part of the method’s contract. Unchecked exceptions may or may not be declared based on developer preference.
  1. Consider the Caller:
  • When designing APIs, consider the exceptions that callers of the methods might need to handle.

The throws clause is an essential part of Java’s exception handling mechanism, helping to document and communicate the potential exceptions that a method may throw. It contributes to the clarity and robustness of Java programs by allowing developers to handle exceptions appropriately.

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.

we do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result

General form of a method declaration that includes a throws clause

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

class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}

Output

inside throwOne
caught java.lang.IllegalAccessException: demo

Leave a Comment