Java exception Handling Instance tutorial _java

Source: Internet
Author: User
Tags error code getmessage throwable

1, what is abnormal?
First, let's take a look at the example in the following diagram:
In this example, the error code exists by dividing the result by 0. Exception caused by dividing by 0: arithmeticexception
Helloexception.java

Package com.yiibai.tutorial.exception;

public class Helloexception {public

  static void Main (string[] args) {

    System.out.println ("Three");

    This division no problem.
    int value = 10/2;

    System.out.println ("two");

    This division no problem.
    Value = 10/1;

    System.out.println ("one");
    
    This is division has problem, divided by 0.
    An error has occurred here.
    Value = 10/0;

    And the following code won't be executed.
    System.out.println ("Let ' s go!");

  }



Run this example and get the result:

You can see the notifications on the console screen. Error notification is very clear, including the line of code information.
Let's take a look at the following procedure through the process in the following diagram:

    • The program runs normally from (1), (2) to (5) steps.
    • In step (6) The program is divided by 0.
    • The program jumps out of the main method, and (7) The line of code has not been executed yet.

We will modify the code for the above embodiments.

Hellocatchexception.java

Package com.yiibai.tutorial.exception;

public class Hellocatchexception {public

  static void Main (string[] args) {

    System.out.println ("Three");

    This division no problem.
    int value = 10/2;

    System.out.println ("two");

    This division no problem.
    Value = 10/1;

    System.out.println ("one");

    try {
      //This division has problem, divided by 0.
      An error has occurred here.      
      Value = 10/0;

      And the following code won't be executed.
      System.out.println ("value =" + value);

    } catch (ArithmeticException e) {

      //The code in the catch block'll be executed
      System.out.println ("Error:" + E . GetMessage ());

      The code in the catch block would be executed
      System.out.println ("Ignore ...");

    }

    This code is executed
    System.out.println ("Let's go!");

  }



To run the sample results:

Three

Two

One

Error:/By zero

Ignore ...

Let ' s go!

We will interpret the following procedure as the following example image process.

    • Steps (1) to (5) are completely normal.
    • The exception occurred in step (6), divided by 0 and there was a problem.
    • It immediately jumps to the catch block to execute the command, and step (7) is skipped.
    • Step (8), (9) is executed.
    • Step (10) is executed.

2. Abnormal hierarchy structure
This is the model of the layered diagram of the Java exception.

The highest class is: Throwable

Two direct subclasses are Error and Exception.

There is a runtimeexception subclass of the exception transfer, including compile-time exceptions in Java. Checking and canceling the check is at compile time, as explained in the implementation example in the next section.

Note: your class should inherit from two branches: Error or exception, not directly from Throwable.

The virtual machine raises this error when a dynamic link fails or some other "hard" failure occurs on the virtual machine. A typical Java program does not catch errors, so the Java program does not throw any errors. Most programs throw and capture objects derived from the exception class. An exception indicates a problem, but these are not serious systemic problems. Most of the programs you write will throw and catch exceptions.

The exception class defines many subclasses in the Java package. These subclasses indicate different types of exceptions that may occur. For example, negativearraysizeexception indicates that the program attempted to create an array with a negative size.

A director's subclass special meaning in the Java language: The RuntimeException class represents an exception that occurs (during a run) in a Java virtual machine. An example of a Run-time exception is a nullyiibaierexception exception, which is raised when a method attempts to access a member of an object through a null reference. Nullyiibaierexception can appear anywhere where a program tries to dereference a reference to an object. The benefits of frequent checking of exception captures far outweigh its costs.

Because run-time exceptions are ubiquitous, the compiler allows run-time exceptions to be not captured and specified when attempting to capture or specify all the time is futile (unreadable and maintainable code).
The Java package defines several runtimeexception classes. You can catch these exceptions, just like any other exception. However, there is no need for a method to specify that it throws a Run-time exception. In addition, you can create your own runtimeexception subclass. Run-time exceptions-The following discussion discusses when and how run-time exceptions are used. 3. Handling Exceptions with Try-catch

Write a class that inherits from exception.

Ageexception.java

Package com.yiibai.tutorial.exception.basic;

public class Ageexception extends Exception {public

  ageexception (String message) {
    super (message);
  }

}
Tooyoungexception.java
package com.yiibai.tutorial.exception.basic;

public class Tooyoungexception extends Ageexception {public

 tooyoungexception (String message) {
   Super ( message);
 }



Toooldexception.java

Package com.yiibai.tutorial.exception.basic;

public class Toooldexception extends Ageexception {public

 toooldexception (String message) {
   super (message);
 }

}

and a static method for checking the age of Ageutils classes.
Ageutils.java

 package com.yiibai.tutorial.exception.basic;
  The public class Ageutils {//is checks the age. If the than is less throw a exception tooyoungexception//If age greater than, the method wi ll throw a exception toooldexception public static void Checkage (int age) throws Tooyoungexception, Toooldexcepti
      On {if (age <) {//If the age is less than, an exception'll be thrown//This method ends here.
    throw new Tooyoungexception (' age ' + age + ' too young ');
      else if (age >) {//If age greater than, an exception would be thrown.
      This is ends here.
    throw new Toooldexception (' age ' + age + ' too old ');
    }//If is between 18-40.
    This code would be execute. System.out.println (' age ' + age + ' ok! ');} 

Check for exceptions and unchecked exceptions:
Ageexception are exception,toooldexception subclasses and TooYoungException2 are ageexception direct subclasses, so they are "Checked Exception"
The ageutils.checkage (int) method has thrown an exception and needs to list their method declarations through the keyword "throws". Or you can declare that you are throwing more levels.
a ageutils.checkage (int) position must also be processed to catch an exception, or to continue throwing it.

"Checked exception" is checked by the "Java Compiler".

There are two options:

Trycatchdemo1.java

Package com.yiibai.tutorial.exception.basic;

public class TryCatchDemo1 {public

  static void Main (string[] args) {


    System.out.println ("Start recruiting ...") ;
    Check Age
    System.out.println ("Check your Age");
    int age = m;

    try {

      ageutils.checkage (age);

      System.out.println ("You pass!");

    } catch (Tooyoungexception e) {

      //do something ...
      System.out.println ("You are too young, not pass!");
      System.out.println (E.getmessage ());

    } catch (Toooldexception e) {

      //do something ...
      System.out.println ("You are too old, not pass!");
      System.out.println (E.getmessage ());}}


In the following example, we will catch the exception (the exception class) through the parent class.
Trycatchdemo2.java

Package com.yiibai.tutorial.exception.basic;

public class TryCatchDemo2 {public

  static void Main (string[] args) {

    System.out.println ("Start recruiting ...") ;
    Check Age
    System.out.println ("Check your Age");
    int age =;

    try {

      //can throw toooldexception or tooyoungexception
      ageutils.checkage (age);

      System.out.println ("You pass!");

    } catch (Ageexception e) {
      
      //If exception occurs, type of ageexception//This catch block would be
      Execute
   system.out.println ("Your age invalid, you don't Pass");
      System.out.println (E.getmessage ());}}


You can also group different exceptions to be handled in blocks if they are the same way for logical program processing.
Trycatchdemo3.java

Package com.yiibai.tutorial.exception.basic;

public class TryCatchDemo3 {public

  static void Main (string[] args) {

    System.out.println ("Start recruiting ...") ;
    Check Age
    System.out.println ("Check your Age");
    int age =;

    try {

      //can throw toooldexception or tooyoungexception
      ageutils.checkage (age);

      System.out.println ("You pass!");

    } catch (Tooyoungexception | Toooldexception e) {
      //Catch Multi exceptions in one block.

      System.out.println ("Your age invalid, you don't Pass");
      System.out.println (E.getmessage ());}}



4, try-catch-finally
We are accustomed to capturing errors through Try-catch blocks. Try-catch-finally to completely handle the exception.

try {

  //do something here

} catch (Exception1 e) {

  //does something here

} catch (Exception2 e) {

  /D o Something here

} finally {

  //finally blocks is always executed
  //does something here

}

Trycatchfinallydemo.java

Package com.yiibai.tutorial.exception.basic;

public class Trycatchfinallydemo {public

  static void Main (string[] args) {

    String text = ' 001234a2 ';

    int value = Tointeger (text);

    System.out.println ("value=" + Value);

  }

  public static int Tointeger (String text) {
    try {

      System.out.println ("Begin Parse Text:" + text);

      An Exception can throw here (numberformatexception).
      int value = integer.parseint (text);

      return value;

    } catch (NumberFormatException e) {//In the case of

      
      ' text ' is not a number.
      This catch block would be executed.      
      SYSTEM.OUT.PRINTLN ("Number format exception" + E.getmessage ());

      Returns 0 If numberformatexception occurs return
      0;

    } finally {

      System.out.println ("End Parse text:" + text);}}



This is the process of the program. Finally blocks are always executed in any case.

5, wrapping the exception

    • We need some classes to participate in this example:
    • Person: Simulates the information that a subject recruits to the company: name, age, sex.
    • Genderexception: Gender abnormality.
    • Validateexception: Abnormal assessment of job seeker.
    • Validateutils: Static method Class comprehensive evaluation of interviewers.
    • If the male age between 18-40 is considered to be effective.

Person.java

Package com.yiibai.tutorial.exception.wrap;

public class Person {public

  static final String MALE = "MALE";
  public static final String FEMALE = "FEMALE";

  private String name;
  private String gender;
  private int age;

  Public person (string name, string gender, int age) {
    this.name = name;
    This.gender = gender;
    This.age = age;
  }

  Public String GetName () {return
    name;
  }

  public void SetName (String name) {
    this.name = name;
  }

  Public String Getgender () {return
    gender;
  }

  public void Setgender (String gender) {
    this.gender = gender;
  }

  public int getage () {return age
    ;
  }

  public void Setage (int age) {
    this.age = age;
  }
}

Genderexception.java

Package com.yiibai.tutorial.exception.wrap;

Gender Exception.
public class Genderexception extends Exception {public

   genderexception (String message) {
     super (message);
   }
}

There are other exceptions to the Validateexception class package.
Validateexception.java

Package com.yiibai.tutorial.exception.wrap;

public class Validateexception extends Exception {
  
  //Wrap a Exception public
  validateexception (Exception e) {
    super (E);
  }

}

Validateutils.java

Package com.yiibai.tutorial.exception.wrap;

Import Com.yiibai.tutorial.exception.basic.AgeUtils;

public class Validateutils {public

  static void Checkperson (person person) throws Validateexception {
    try {

      / /Check age.
      Valid if between 18-40
      //This method can throw toooldexception, tooyoungexception.    
      Ageutils.checkage (Person.getage ());

    } catch (Exception e) {
      
      //If not valid
      //Wrap This Exception by Validateexception, and throw
      throw new Vali Dateexception (e);

    }

    If is Female, ie invalid.
    if (Person.getgender (). Equals (Person.female)) {

      genderexception e = new Genderexception ("Do not accept women"); C17/>throw new Validateexception (e);

    }
  }



Wrapperexceptiondemo.java

Package com.yiibai.tutorial.exception.wrap;

public class Wrapperexceptiondemo {public

  static void Main (string[] args) {
    
    //One participant recruitment.
    person who = new Person ("Marry", Person.female);

    try {

      //exceptions may occur here.
      Validateutils.checkperson (person);

    } catch (Validateexception wrap) {

      //get the real cause.
      May is tooyoungexception, toooldexception, genderexception
      Exception cause = (Exception) wrap.getcause ();

      if (cause!= null) {
        System.out.println ("Not pass, Cause:" + cause.getmessage ());
      } else {
        System.out.println (wrap.getmessage ());}}}



6, RuntimeException and subclasses runtimeexception classes and their subclasses are "unchecked exceptions". It is not checked by the Java compiler at compile time. In some cases, you can inherit from this branch to write your own exception.

Below are some classes that belong to the RuntimeException branch (not all of this, of course).
Some examples of handling this type of exception are:

6.1-nullyiibaierexception
This is the most common exception, which usually results in an error in the program. The exception is thrown when you call the method or access the field of an empty object.
Nullyiibaierexceptiondemo.java

 package com.yiibai.tutorial.exception.runtime;
  public class Nullyiibaierexceptiondemo {//For example, this can return null string.
    public static String getString () {if (1 = 2) {return "1==2!!";
  return null;
    public static void Main (string[] args) {/* is ' an object ' that references ' not NULL.

    String Text1 = "Hello exception";
    Call the method retrieves the string length.

    int length = Text1.length ();

    System.out.println ("Length Text1 =" + length);
    This is the object that references null.
    
    String Text2 = getString ();
    Call the method retrieves the string length.
    Nullyiibaierexception'll occur here. It is a exception occurs at runtime (type of runtimeexception)//Javac compiler No does you to use a force

    Atch blocks to handle it length = Text2.length ();
  System.out.println ("finish!"); }

}

Run the results of the sample:

In reality, as with other exceptions, you can use Try-catch to catch and handle this exception. However, this is mechanical and usually we should check to make sure that the object is not null before using it.
You can correct the code above so that it resembles the following to avoid NULL pointer exceptions:

This is a null object.
String Text2 = getString ();

Check to make sure ' Text2 ' are is not null.
Instead of using Try-catch.
if (Text2!= null) {
 length = Text2.length ();
}

6.2-arrayindexofboundexception
This exception occurs when you attempt to access an array element of an invalid index. For example, an array has 10 elements to access, but you are accessing an element with an index of 20.
Arrayindexofboundsexceptiondemo.java

Package com.yiibai.tutorial.exception.runtime;

public class Arrayindexofboundsexceptiondemo {public

  static void Main (string[] args) {

    string[] STRs = new String [] {"One", "two", "Three"};

    Access to the element has index 0.
    String str1 = strs[0];

    System.out.println ("String at 0 =" + str1);

    
    Access to the element has index 5.
    Arrayindexofboundsexception occur here.
    String str2 = strs[5];

    System.out.println ("String at 5 =" + str2);

  }



To avoid arrayindexofboundsexception, we should check the array instead of using Try-catch.

if (Strs.length > 5) {
  String str2 = strs[5];
  System.out.println ("String at 5 =" + str2);
} else {
  System.out.println ("No Elements with index 5");
}

The above is the entire content of this article, I hope to help you learn.

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.