Java Exception Handling Mechanism (2)

Source: Internet
Author: User

Java Exception Handling Mechanism (2)

1. Role of throw

Class Usre {

Private int age;

Public void setAge (int age ){

If (age <0 ){

RuntimeException e = new RuntimeException ("Age cannot be negative"); // generate an exception object

Throw e; // throw

}

This. age = age;

}

}

Class Test {

Public static void main (String args []) {

User user = new User ();

User. setAge (-20 );

}

}

Throw is used to throw an exception object.

2. Role of throws


Class Usre {

Private int age;

Public void setAge (int age) throws Exception {

If (age <0 ){

Exception e = new Exception ("Age cannot be negative"); // generate an Exception object

Throw e; // throw

}

This. age = age;

}

}

Class Test {

Public static void main (String args []) {

User user = new User ();

Try {

User. setAge (-20 );

}

Catch {

System. out. println (e );

}

}

}


Throws: When an exception may occur in a function, you can use try... catch can handle code that may generate exceptions. It can also be declared after the function to generate an Exception (declaration method: add the possible Exception type after throws). Once declared, therefore, this function has no responsibility to handle this exception, but to handle this exception from the called place.



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.