Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I throw an exception for the whole class instead of doing it method by method

I'm writing a program in Java, and nearly every method in one of my classes is written like:

public void doStuff() throws AWTException{}

Is there a way for me to get rid of the extra step of typing throws AWTException for each method, and somehow do it for the entire class?

like image 968
Dream Lane Avatar asked Dec 10 '10 05:12

Dream Lane


People also ask

How do you throw an exception without a try catch?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

How do you throw all exceptions in Java?

Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.

What are the two main ways to deal with exceptions in a method?

You can either use the try-catch-finally approach to handle all kinds of exceptions. Or you can use the try-with-resource approach which allows an easier cleanup process for resources.

How do you throw an exception from a method?

The throws keyword is used to declare which exceptions can be thrown from a method, while the throw keyword is used to explicitly throw an exception within a method or block of code. The throws keyword is used in a method signature and declares which exceptions can be thrown from a method.


3 Answers

if you throw exception with class level then how you identify that on which type of exception is thrown by method... or on which method it throw exception.

so it is not allow in java...and also its not a good coding with java

like image 24
Ravi Parmar Avatar answered Oct 30 '22 04:10

Ravi Parmar


Sorry, No. There is no way to do this in Java.

like image 50
Asaph Avatar answered Oct 30 '22 05:10

Asaph


You can by throw exception at constructor level. You can see how FileInputStream force us to throw IO exception while creating object of it.

like image 1
Aditya Avatar answered Oct 30 '22 06:10

Aditya