Java Learning Diary 9-Exceptions

Source: Internet
Author: User
Tags throwable

Exception (Exception)

First, what is an anomaly?

Exceptions are errors in the program, such as array bounds, access to null pointers, and so on. In Java , everything is objects, exceptions are no exception. All exceptions are an instance object derived from the Throwable class.

Ii. Classification of anomalies

In the anomalous world, there are two major schools. One is called the error class, the other faction is called the Exception class, they all inherit from the throwable class. There are also two major branches underthe exception class , theIOException class and the runtimeexception class .

RuntimeException is an exception caused by the error of the program itself.

IOException is not a problem with the program itself, but an exception due to an IO error.

Example:

RuntimeException

IOException

Array access out of bounds

Attempting to open a file that does not exist

Accessing a null pointer

Attempting to read data at the end of a file

Wrong type conversions

runtimeexception class and it's Uncle Error class Compare Pro, nephew are collectively referred to as unchecked exceptions ( unchecked Exception ), plain English is not you to check, without your tube abnormalities. and IOException and its brothers and uncles are obviously not all the way, known as checked anomalies (checked Exception), that is, you have to control it.

Third, exception handling (Exception handing)

As we said before, we don't have to check for exceptions, so here's just how we deal with checked exceptions.

(1)throws

First, you have to declare it. The method should declare all possible exceptions at its header with the throws+ exception name .

4 scenarios in which exceptions are thrown:

1. Call a method that throws a checked exception.

2. Errors are found during the program's operation and a checked exception is thrown with the throws statement

3. Program error, such as array access out of bounds, will automatically throw arrayindexoutofboundsexception

Internal error in 4.Java virtual machine and run-time library

As an example:

1 Class myanimation{2      Public Image LoadImage (String s)throws  IOException, eofexception3    {4     ...... 5     }6 }

(2) Throw an exception with the Throw keyword

1String ReadData (Scanner in)throwseofexception{2     ...3      while(...) {4         if(!In.hasnext ())5         {6             if(n<len)7             Throw Neweofexception ();8         }9     }Ten}

(3) Custom exceptions

When the exception provided by Java does not meet the need, you can DIY a

1 //define a Fileformatexception class2 classFileformatexceptionextendsioexception{3      Publicfileformatexception () {}4      Publicfileformatexception (String gripe) {5         Super(gripe);6     }7 }8 //The following throws a custom exception9String ReadData (Scanner in)throwseofexceptionTen { One     ... A      while(...) { -         if(ch = =-1){ -             if(n<len) the             Throw Newfileformatexception (); -         } -     } -     returns; +}

(4) Catching exceptions

The light throws the exception and cannot ignore it, so you have to catch it and deal with it.

1 // catching exceptions with Try-catch statement blocks 2 Try {3    code4}5catch(Exceptiontype e) {  6for this       type7 }

If the code in the try statement block throws an Exception class that is described in the catch clause, then

1) The program skips The other code of the try statement block.

2) The program executes the processor code in the catch clause

(5) Anomaly-method inside and outside

For exceptions, you can use a try-catch statement block inside a method to capture and process it, and if you do not want to handle it inside a method, you can declare an exception that might be thrown in the method header, and pass the exception to the code that invokes the method to handle it. in short, is the method inside with Try-catch Treatment, method external throws throw.

(6) Capturing multiple exceptions

1 Try {2    code3}4catch(FileNotFoundException |  Unknowhostexception e) {5    ... 6 }7catch(IOException e) {8    ... 9 }

(7) Finally

1 Try {2    ... 3 }4catch(IOException e) {5    ... 6 }7finally{8    ... 9 }

The code in the finally statement block executes, whether or not an exception occurs.

Try-catch,try-catch-finally,try-finally three combinations,1, 3 combinations more commonly used

(8) A try statement block with resources

A try block with resources closes the resource automatically when it exits, which often eliminates the finally statement

1 Try New Scanner (new  fileinputstream ("File Path"))) {2while     (In.hasnext () ) 3     System.out.println (In.next ()); 4 }

Note: ╮(╯▽╰)╭ This article extensively refer to "Java Core Technology Volume I"

Java Learning Diary 9-Exceptions

Related Article

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.