What is meant by the throws clause?Where & how is it used?

Greetings,

In Java, all methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. In the Java system, throwable objects are instances of any subclass of the Throwable class.

If you attempt to throw an object that is not throwable, the compiler refuses to compile your program and displays an error message.

The throws clause specifies that the method can throw an EmptyStackException. As you know, the Java language requires that methods either catch or specify all checked exceptions that can be thrown within the scope of that method.


- Stack Overflow

how does the try catch and finally work in a run time program???

how does the try catch and finally work in a run time program???

A try/catch/finally block resembles a if/if else/else block in structure, however in functionality it it quite different. The code scoped within the try block attempts to execute, and if an error (exception) is thrown, the stack will begin to unwind, and will stop unwinding if the catch parameter names the thrown error. Exception is the superclass to all exceptions and catches everything. The catch block takes over then and only then. The finally block always executes, it is good for closing files and ports, for example. If there is no matching exception the application will quit, leaving your system in a potentially arbitrary state. The catch block is a good place for stack trace printouts and otherwise error reporting.

PS: Relying on exceptions is poor programming style. Never pass an exception silently.

Here is the try/catch/finally format:

try {
    // ...
} catch (Exception e) {
    // ...
} finally {
    // ...
}

In case there is any confusion, I want to stress that the resemblance between try/catch/finally and if/then/else is purely superficial, and the two should not be confused. As Sean noted, the finally clause always executes (barring some extremely complex and extremely unlikely constructions that code lawyers have come up with), so it's not like an else at all, and the catch executes iff the try block encounters an exception that the catch block can handle.

You'll mostly likely be dealing with catching the checked exceptions at this stage in your programming. That's not hard to understand, but it can lead to some complex code. For example, trying to open a file, you might end up with something like this:

boolean fail;
		
		BufferedReader reader=null;


		try{
			reader = new BufferedReader(new FileReader(file));
			fail = false;
		}
		catch (IOException e)
		{
			System.out.print("Error opening "+ getName() + " "+ e.toString());
			e.printStackTrace();
			fail = true;
		}
		if (fail) return;

		// code here to read the file - another try block required! - or just
		// return the BufferedReader and let another method do the reading

If I hit the catch block, I want to report the failure. I'm doing the minimal version of that here - in a deployed program, to be used by actual users, the reporting would probably involve popping up a warning window, offering to retry, and ideally, logging the failure as well as possible. That's not enough, however. If I hit the catch block, I know that reader is a null object - I don't want to continue on to actually trying to get data out of it, so I set a flag which tells me "Get out of here" - return from the method. Again, in a deployed application, I might instead throw an exception up to the method that called this one, so that it would know that this file-opening method had failed. That method would then have to know how to handle this problem. Of course, this takes us into writing your own exceptions, and that's a kettle of fish of a different color. You'll worry about that later, when you get into the actual engineering.

For now, what you need to know is that some operations are considered "risky", and they throw exceptions. When you perform those operations, you'll need to handle those exceptions, and the best way to do that in a classroom assignment is to just report the failure and move on. When you're writing programs for other people to use, you'll worry about actually dealing with the situations in the program.

Member Avatar for vjcagay

the Throws clause is a way to prepare your method in case it creates an exception.
:)

the Throws clause is a way to prepare your method in case it creates an exception.
:)

Not exactly. It's more a way to warn other classes that the method they're calling might emit an exception that they'll have to handle. It's used to delegate responsibility for error conditions. For example, if you write a method that opens a file, it's fair to put the responsibility on the calling class to make sure that the file exists - therefore, you'd want to throw a FileNotFoundException (rather than, say, catching and eating the exception). On the other hand, if you have a method that originates a request to open a file (say, it throws up a filechooser and offers to crack open a text file) then that method should not throw a FileNotFoundException (where would it throw it to?), but it should handle it in a Try/Catch block. Presumably, handling it would mean reporting the issue to the user and offering to try again.
So throwing an exception is not just a way to make an exception go away, and it's certainly not a way to get rid of some annoying checked exception. It's a way to make sure that the exception is returned to where it can be handled correctly.

you can use the throws clause is used to say that a method can throw a certain exception to the caller. the caller will then have to handle this exception either by rethrowing it or handling it through a try catch block

how does the try catch and finally work in a run time program???

Try Catch and Finally are three blocks used in exception handling programs.
Try Block is the block inside which the error may occur or in simple words the code written inside the try block is the code which may throw an exception if the exception occurs then this exception is thrown to the catch block and the finally block is the block which runs even the code in the try block throws an exception or notand which excecutes after the try catch block so called as finally

Member Avatar for vjcagay

i think that using the try catch finall block is more efficient than using the throws
clause..
:)

i think that using the try catch finall block is more efficient than using the throws
clause..
:)

It's nothing to do with "efficiency". If your method can sensibly handle the Execption then it should catch it and handle it. If it can't sensibly handle it it should throw it up to the caller.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.