This article source http://wenda.tianya.cn/wenda/thread? Sort = wsmopts & tid = 656f1ab9991050dd
Although the two seem to have only one s difference, their functions are completely different.
//// Java Exception Handling Method ///////////////////////////////
If an exception occurs in java code, the jvm will throw an exception object, causing program code interruption. In this case, 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.
However, if an exception occurs in a method but you do not know how to handle it, the method will be interrupted when an exception is thrown, the exception is thrown to the caller of this method. This is a bit like a subordinate who cannot handle the problem, but it is handed over to the boss. This situation is called an exception avoidance.
However, this makes it dangerous to call this method, because no one knows when the method will lose an exception to the caller, so when defining the method, you need to use throws in the method header to declare the exceptions that this method may avoid.
Void fun () throws ioexception, sqlexception
{
...
}
This means that two exceptions may be thrown out of the fun method, so you will be prepared when calling fun, for example, you can
Try
{
Fun ();
} Catch (ioexception E)
{
} Catch (sqlexception E)
{
}
////////////////////