Using the throws keyword

In the previous examples the exceptions were handled approximately where they occur. This can lead to some fairly complex code. For instance if you are doing a large amount of I/O you will end up with huge amounts of try/catch blocks that can soon make your code hard to read.

The use of the throws keyword allows you to pass exceptions up the stack to calling methods. The throws keyword is appended to a method name and is followed by the Exceptions that might be thrown. Thus typically you might have a method with a file operation thus

public void amethod() throws IOException{
	FileOutputStream fout = new FileOutputStream("test.txt");
	fout.close();
	}
}

Notice how the throws clause comes after the parameter parenthesis and before the curly brackets. This sample code simply creates a file in the underlying operating system called test.txt. It is the close method of the FileOutputStream class that actually writes the file to the operating system. Without the throws clause this code would not even compile. Note that the calling method must catch the declared exception.

Last modified: Thursday, 24 July 2014, 2:54 PM