Exception handling
1. Exception Handling Syntax
Try
{The program statement to check;}
catch (Exception E) (Note: Exception class object name commonly used Exception e)
{The strenuous statement when the exception occurred;}
Finally
{The program code is bound to execute;}
Application code:
public class Java0 {
public static void Main (String args[])
{
Try//Check the code of this program block
{
int arr[]=new int [5];
arr[10]=7; There will be an exception
}
catch (ArrayIndexOutOfBoundsException e)
{
SYSTEM.OUT.PRINTLN ("Array out of bound range!") ");
}
Finally//This program code is bound to be executed
{
System.out.println ("This is going to be done!") ");
}
System.out.println ("Main () method end!" ");
}
}
Code:
2. Throw exception syntax
Try
{if ()
Throws new Exception ("processing statement");}
Catch
{System.out.println (e):}
Application code:
Throw an exception in the program
public class Java2 {
public static void Main (String args[])
{
int a=4,b=0;
Try
{
if (b==0)
throw new Exception ("An arithmetic exception");//Throws an exception
Else
System.out.println (A + "/" +b+ "=" +a/b);
}
catch (Exception e)
{
System.out.println ("Throw exception:" +e);
}
}
}
Code:
3. Write your own exception class
Class Exception classes name extends Exception
{...
Super ();//Call the construction method of the parent class. };
Eg: Write your own exception class CuO, and then call
In addition to the 0 operation of the program, the program throws an exception and outputs "the divisor is 0, the program is wrong." ”
Class Cuo extends Exception
{
Public Cuo (String Cuo)
{
Super (CuO);
}
}
public class Java5 {
public static void Main (String args[])
{
int a=5,b=0;
Try
{
if (b==0)
{
throw new Cuo ("The divisor is 0, the program is wrong!") ");
}
Else
{
System.out.println ("The quotient of two numbers is:" +a/b);
}
}
catch (Cuo e)
{
System.out.println (e);
}
}
}
Code Execution:
Summary of Java study notes for winter vacation 2