Difference between throw and throws in Java
//// Java Exception Handling Method ///////////////////////////////
In JavaCodeIf an exception occurs, the JVM will throw an exception object, causingProgramCode interruption. At this time, the JVM is doing the following operations: create an exception object and then throw it, for example:
Int I = 1;
Int J = 0;
Int res = 0;
Res = I/J; // An error occurred while division by 0.
System. Out. println (RES );
These five sentences will be interrupted when the code runs to the fourth sentence, because the JVM throws an exception.
/// Throw ///////////////////////////////// ////////
Manually throw an exception
But sometimes some errors do not seem to be errors in JVM, for example
Int age = 0;
Age =-100;
System. Out. println (AGE );
It is normal to assign values to integer variables, but in our eyes it is not normal. Who's age will be negative.
Therefore, we need to manually trigger exceptions, which is the role of throw.
Int age = 0;
Age =-100;
If (age <0)
{
Exception E = new exception (); // create an exception object
Throw E; // throw an exception
}
System. Out. println (AGE );
/// Throws ///////////////////////////////// //
Exceptions that can be avoided by declaring Methods
if an exception is thrown, it must be processed. Therefore, there is a try-catch in Java.
however, sometimes an exception occurs in a method, but you do not know how to handle it. if an exception is thrown, the method is interrupted, the exception is thrown to the caller of this method. This is a bit like a subordinate who can't handle the problem and is handed over to the boss. This situation is called avoiding exceptions.
but this makes it dangerous to call this method, because no one knows when this method will lose an exception to the caller, therefore, when defining a method, you need to use throws in the method header to declare the exception that this method may avoid
void fun () throws ioexception, sqlexception
{< br>...
}< br> This indicates that two exceptions may be thrown in the fun method, so you will be prepared to call fun, for example, you can
try
{< br> fun ();
}catch (ioexception e)
{< BR >}catch (sqlexception E)
{< BR >}