JAVA31: Exception

Source: Internet
Author: User
Tags finally block

Java Exception handling mechanism

Top-level class for Throwable class exceptions

Sub-class

Error: System-level errors

Stack memory Overflow

Exception: Program-level errors

Can be solved by capturing the mechanism class




Try Statement

try{

Code snippets that may appear to be abnormal

}

try{} This is the statement that found the problem

Catch statement

catch (Exception_type e) {

Code snippet to solve the problem

}

Catch statements are used to capture occurrences in a try statement and to resolve that exception, a catch statement block can appear multiple times

Catch exception: You should include exception in the last catch to ensure that the program does not break because it does not catch an unknown exception, and that the exception should be placed on the last of all the catch.


Package day31;public class demo01 {public static void main (String[]  args) {try{string str = null; System.out.println (Str.length ());} catch (nullpointerexception e) {System.out.println ("null pointer exception");} System.out.println ("Over");try{string str1 =  ""; System.out.println (Str1.length ()); System.out.println (Str1.charat (3));} catch (nullpointerexception e) {System.out.println ("null pointer exception");} catch (stringindexoutofboundsexception e) {System.out.println ("string index out of  Bounds exception ");} System.out.println ("Over");try{string str2 =  "ABC"; System.out.println (Str2.length ()); System.out.println (Str2.charat (1)); System.out.println (Integer.parseint (STR2));} catch (nullpointerexception e) {System.out.println ("null pointer exception");} catch (stringindexoutofboundsexception e) {System.out.println ("String index out oF bounds exception ");} catch (exception e) {System.out.println ("Unknown error");} System.out.println ("Over");}}




Throw statement

Throw e;

Throw an instance that is used to actively throw an exception

The method that we define has an error during operation and how this error is resolved should be determined by the caller

When we encounter a non-logical operation, we can treat it as an exception.

Package Day31;public class Person {private int age;public int getage () {return age;} public void Setage (int ages) {if (age > +) {throw new RuntimeException ("illegitimate");} This.age = Age;}} Package Day31;public class Demo02 {public static void main (string[] args) {person p = new person ();p. Setage (100);}} Package Day31;public class Demo03 {public static void main (string[] args) {person P1 = new person (); try {p1.setage (10001); } catch (Exception e) {System.out.println (e);}}}



THORWS statement

We may have an error in the method we define, whether or not we have thrown it, but as long as the exception that occurs in the method is not handled in the method, we usually declare that the method is a colleague stating the exception that might be thrown, informing the caller that it must capture

Package day31;/** * * Define a method to declare an exception to be thrown * Use the throws statement */public class Demo04 {/** * When other methods called in the method declare throws, * in the current method Try-catch resolve this Problem * Declaring throws on the current method continues to throw the exception outward (do not throw the JVM directly on main) */public static void Main (string[] args) {//Connect to database try {connectiondb ("192.168.1.2");} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Save Data"); System.out.println ("OK");} /** * Connection Database *throws can throw more than one exception, each exception with, separate * Do not define the exception that is thrown in the middle of the method * * Method throws what exception, throws will define what exception * */public static void Connectio NDB (String URL) throws Exception{if ("192.168.1.1". Equals (URL)) {System.out.println ("database connection succeeded");} Else{//throw New Exception ("Connection Database Exception");}}}


When you throw runtimeexception and its subclasses in the package day31;/** * method, the method declaration definition is not required throws *runtimeexception is called a non-check exception * that is when the exception is thrown when the compilation process is found. is a compile-through * but except for this other thrown exception type if you do not write throws or catch compile-time * Common Runntimeexception subclass *nullpointerexception * ArrayIndexOutOfBoundsException *numberformatexception *classcastexception */public class Demo05 {public static void Main (string[] args) {}public static void Connectiondb () {throw new RuntimeException ("Runerror");}}


Finally block

finally{

Code Snippets

}

Finally appears at the end of the try statement

Statements in a finally block are necessarily performed regardless of whether an exception occurs in a try

For finishing work

package day31;public class demo06 {public  Static void main (String[] args) {try{string str = null; System.out.println (Str.length ());} catch (exception e) {System.out.println ("Error");} finally{//regardless of whether the statement in the try is an error, finally the block will execute SYSTEM.OUT.PRINTLN ("finally");} System.out.println ("Over");}} 
package day31;public class demo07 {public  Static void main (String[] args) {try{string age =  "ABC"; System.out.println ("Connectmysql"); System.out.println ("Saveage:" +integer.parseint (age));} catch (exception e) {System.out.println ("Error");} finally{//Finishing Work   closing database connection System.out.println ("CloseConnection");} System.out.println ("Exitsystem."); System.out.println ();try{string age1 =  "123"; System.out.println ("Connectmysql"); System.out.println ("Saveage:" +integer.parseint (Age1));} catch (exception e) {System.out.println ("Error");} finally{//Finishing Work   closing database connection System.out.println ("CloseConnection");} System.out.println ("Exitsystem.");}} 
Package Day31;public class Demo08 {public static void main (string[] args) {System.out.println (Test (NULL) + "," +test ("0") + "," +test (""));//102//but finally must execute so 4,4,4}public static int test (String str) {Try{return Str.charat (0)-' 0 ';} catch (NullPointerException e) {return 1;} catch (RuntimeException e) {return 2;} catch (Exception e) {return 3;} finally{//must execute return 4;//so do not add return in the finally or method can only return the return in finally}}}



Exception handling When overriding a method

The throw of some exceptions is declared by throws in the parent class method

Subclasses can not declare throws when overridden

Subclasses can throw exceptions that are thrown by a parent class when overridden by a subclass class

Parent class throws RuntimeException

Subclasses can throw NullPointerException

Subclasses can only throw partial exceptions thrown by the parent class when overridden

Parent class throws of 3

Subclasses can throws 2 of


Subclass overrides cannot throw extra exceptions that are not thrown in the parent class method

Parent class throws of 3

Subclass cannot throws 4

Subclass overrides are parent exceptions that cannot throw exceptions thrown in a parent class method

Parent class throws RuntimeException

Subclasses cannot throws Exception


Package Day31;public class Demo08 {public static void main (string[] args) {System.out.println (Test (NULL) + "," +test ("0") + "," +test (""));//102//but finally must execute so 4,4,4}public static int test (String str) {Try{return Str.charat (0)-' 0 ';} catch (NullPointerException e) {return 1;} catch (RuntimeException e) {return 2;} catch (Exception e) {return 3;} finally{//must execute return 4;//so do not add return in the finally or method can only return the return in finally}}}


This article from the "Romantic Smile" blog, reproduced please contact the author!

JAVA31: Exception

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.