throws
keyword is used to specify the types of exceptions that a method might throw during execution.
IOException
, SQLException
etc).
return_type methodName(parameters) throws ExceptionType1, ExceptionType2, ...
{
// method body
}
ExceptionType1, ExceptionType2, ...
are the types of exceptions that the method declares it might throw.
import java.io.FileInputStream;
import java.io.IOException;
public class ThrowsDemo
{
// Method declares that it may throw IOException
void readFile() throws IOException
{
// Using try-with-resources ensures FileInputStream is closed automatically
try (FileInputStream fis = new FileInputStream("test.txt"))
{
// Read first byte from the file
int data = fis.read();
System.out.println("First byte of the file: " + data);
}
}
public static void main(String[] args)
{
try
{
ThrowsDemo obj = new ThrowsDemo();
// Caller method handles the IOException thrown by readFile()
obj.readFile();
}
catch (IOException e)
{
// Exception is caught and handled here
System.out.println("Exception handled: " + e);
}
}
}
Exception handled: java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
readFile()
method declares throws IOException
.
IOException
while reading the file.
main()
method, we call readFile()
inside a try-catch
block.
test.txt
is not found, an exception will be caught.
throws
keyword is used in a method declaration to declare the exceptions that the method might throw.
void myMethod() throws IOException, SQLException { }
throws
does not throw an exception by itself; it only informs the caller about possible exceptions.
try-catch
or declare it using throws
.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.