Summary of Java study notes for winter vacation 2

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.