Answer the question
In order to leave comments, you need to log in
Is there any reason to use the throws operator?
Greetings!
I continue to read Schildt's book "Java 8. The Complete Guide"
At the same time, of course, I experiment with the examples given. I was interested in such an example of using the operator throws
Schildt writes that if a method generates an exception that it does not process itself, then in order for the program to compile successfully, it is necessary to supplement the method declaration with an indication of the throws operator and the list of exceptions that it generates, but leaves for analysis to subsequent code.
Quote from the book "The following is an example of a badly written program that tries to
throw an exception that is not caught in the program itself. This program
cannot be compiled because it does not contain the operator throws
,
which declares an uncaught exception.
This program contains an error and therefore cannot be compiled.
c l a s s Throws Demo {
s t a t i c void t h r owOn e ( ) {
)
S y s t em . out . p r i n t l n ( " B теле ме тода t h r owOne ( ) . " ) ;
throw new I l l eg alAcc e s s Excep t i on ( " дeмoнc тpaция " ) ;
puЫ i c s ta t i c void ma i n ( S t r ing a r gs [ ] ) {
throwOne ( ) ;
throwOne ( )
an exception of type IllegalAccessException
. And secondly, define main( )
a statement block in the method try/catch
to catch this exception. Below is the corrected code for this program." static void testException()
{
throw new ArithmeticException("Арифметическая ошибка"); // тут порождаем исключение
}
public static void main(String[] args) {
// TODO code application logic here
try{
testException();
}
catch(ArithmeticException e)
{
System.out.println(e + "Vot tut"); // здесь отлавливаем исключение, которое породил наш метод
}
}
Answer the question
In order to leave comments, you need to log in
In order to learn how to work with the interception of specific exceptions, it is not necessary to write a program with an error. You can just directly raise this error (exception) with the throw command.
That is, in this case, the task is not to throw exceptions, but to learn how to catch them correctly.
And here is an example of how you do a catch before throwing an exception.
In a normal program, throw is not needed, it is needed temporarily, to debug your catch
"So now it's not clear to me why use the trows operator, because everything works without it?"
There are checked exceptions (checked), and there are not checked (unchecked). From here and dance)
Easy to google.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question