JavaSE-14 Exception Handling

Source: Internet
Author: User
Tags finally block throw exception

Learning Essentials
    • Handling Exceptions using try-catch-finally
    • Throwing exceptions using throw, throws
    • Exceptions and their classification
    • log4j Logging

Definition of Exception 1 exception

An exception is an abnormal event that occurs during the course of a program's operation, which interrupts a running program.

2 Exceptions in the program

Is there a problem with this calculator code below?

public class Calculator {public    static void Main (string[] args) {        Scanner in = new Scanner (system.in);        System.out.print ("Please enter dividend:");        int num1 = In.nextint ();        System.out.print ("Please enter the divisor:");        int num2 = In.nextint ();        System.out.println (String.Format ("%d/%d =%d", NUM1, num2, NUM1                /num2));        System.out.println ("Thanks for using this program! ");    }}

  

How can you solve this problem with the knowledge you have learned?

public class Calculator {public    static void Main (string[] args) {        Scanner in = new Scanner (system.in);        System.out.print ("Please enter dividend:");        int num1 = In.nextint ();        System.out.print ("Please enter the divisor:");        int num2 = 0;        if (In.hasnextint ()) {            num2 = In.nextint ();            if (0 = = num2) {//If the divisor of the input is 0                System.err.println ("The input divisor is 0, the program exits. ");                System.exit (1);            }        } else {//input divisor is not an integer            System.err.println ("The input divisor is not an integer, the program exits.") ");            System.exit (1);        }        System.out.println (String.Format ("%d/%d =%d", NUM1, num2, NUM1                /num2));        System.out.println ("Thanks for using this program! ");    

  

There are drawbacks to dealing with exceptions: bloated code, a lot of effort to "plug holes", and the difficulty of blocking all "holes". How to solve this problem? Use Java exception handling mechanism!

Exception handling 1 Java exception handling mechanism

The Java programming language uses exception-handling mechanisms to provide the program with the ability to handle errors.

Java exception handling is implemented by 5 keywords: try, catch, finally, throw, throws.

2 Try-catch

Grammatical structure

try{//Code Snippet 1}catch (Exception type ex) {     //code snippet for handling exceptions}//code snippet 2

Try-catch three scenarios for catching exceptions

    1. Code Snippet 1 does not catch an exception, code in the catch block does not execute, code snippet 2
    2. Code Snippet 1 captures an exception, produces an exception object, performs an exception type match, and enters the catch block to execute the exception-handling code. After processing, continue with code Snippet 2.
    3. Code Snippet 1 captures an exception, produces an exception object, does not match the exception object, and the program interrupts the run

Processing information in a catch block

1. Customizing processing information

SYSTEM.ERR.PRINTLN ("An error occurred: the divisor and divisor must be integers and the divisor cannot be zero.") ");

2. Call the method to output exception information. Common methods for Exception objects

Method name

Description

void Printstacktrace ()

Stack information for output exceptions

String GetMessage ()

Returns the exception information description string, which is part of the printstacktrace () output information

3. Common exception types

different often class type

say Ming

Exception

The parent class of the exception hierarchy

ArithmeticException

Arithmetic error scenarios, such as dividing by zero

ArrayIndexOutOfBoundsException

Array subscript out of bounds

NullPointerException

Attempting to access a null object member

ClassNotFoundException

Unable to load the required classes

IllegalArgumentException

Method received an illegal parameter

ClassCastException

Object coercion type conversion error

NumberFormatException

Numeric format conversion exception, such as converting "ABC" to Digital

3 try-catch-finally

Syntax description

    • Does the exception occur and is executed?
    • The only cases not performed: System.exit (1)

There is a return try-catch-finally

4 multi-heavy catch

Multiple types of exceptions are thrown in a try block

    • Order of the Catch statements: first Subclass stepfather Class
    • Match in order when an exception occurs
    • Only the first catch statement that matches the exception type is executed

Execution process

5 questions and on-machine exercises

Question 1:The return statement exists in the Try-catch block, whether the finally block is also executed, and, if so, the order of execution.

Question 2:What is the only case where the finally block is not executed in the try-catch-finally block?

On-Machine practice

Requirements Description:

    1. Follow the console prompts to enter any number between the two, the program will output the corresponding movie film name.
    2. Judging by the keyboard input. If the input is correct, the output corresponds to the movie name. If you enter an error, you are given an error message.
    3. The "Welcome to Fox Cinema" statement is output regardless of whether the input is correct.

declaring exceptions

How do I notify the caller if an exception is thrown in a method body?

Throw exception

In addition to the system automatically throwing exceptions, some problems require programmers to throw exceptions themselves.

Java exception Classification questions and on-machine exercises

Issue 1: Say 5 common run-time exceptions

Question 2: What is the difference between throw and throws?

on-machine exercise : Throwing exceptions with throw

Requirements Description :

    • Defining the Person class
    • Age is judged in setage (int age) and throws an exception if it is assigned directly from 1 to 100.
    • Create an object in the test class and call the Setage (int age) method, using Try-catch to catch and handle the exception.

Log4j1 Logs (log)
    • It is mainly used to record some important operation information in system operation.
    • Easy to monitor system operation, help users to identify and avoid possible problems in advance, or to find out the cause of the problem after the log.
2nd Log Classification
    • SQL logs, exception logs, business logs, and so on.
3 log4j

Log4j is an open source project for Apache and is a very good open source logging tool.

    • Control the output level of the log
    • Control log information Delivery destination is the console, files, etc.
    • Control the output format of each log
4 Steps to use log4j

First step: Project create lib directory, put in log4j jar file

Step Two: Create the log4j.properties file in the SRC directory

Step Three: Configure log information

# # # Set Logger output level and output Destination # # #日志记录器输出级别: fatal > Error > Warn > Info >debug#log4j.rootlogger=debug, stdout, LogFile # # # to output log information to the console # # # #日志信息输出到控制台 #log4j.appender.stdout=org.apache.log4j.consoleappender# information print to System.err # Log4j.appender.stdout.target=system.err# specifying the log layout type #log4j.appender.stdout.layout=org.apache.log4j.simplelayout # # # Output log information to file: Etc.log # # # #日志信息写到文件中 #log4j. appender.logfile=org.apache.log4j.fileappender# Specifies the file name of the log output # log4j.appender.logfile.file=etc.log# Specifies the conversion mode #log4j.appender.logfile.layout=org.apache.log4j.patternlayout# Specify the log layout type #log4j.appender.logfile.layout.conversionpattern=%d{yyyy-mm-dd HH:mm:ss}%l%F%p%m%n

  

Fourth step: Logging log files using log4j

public class Log4jdemo {    //Create Logger object    private static Logger Logger = Logger.getlogger (Log4jDemo.class.getName ( ));    public static void Main (string[] args) {        try {            Scanner in = new Scanner (system.in);            System.out.print ("Please enter dividend:");            int num1 = In.nextint ();            System.out.print ("Please enter the divisor:");            int num2 = In.nextint ();            System.out.println (String.Format ("%d/%d =%d", NUM1, num2, NUM1                    /num2)),        } catch (Exception e) {            logger. Error ("Exception occurred", e);//record log        } finally {            System.out.println ("Thank you for using this program!") ");        }    }}

  

5 on-Machine exercises

Requirements Description: Use log4j to output logs to the console and file.

    • Enter dividend and divisor as prompted by the console
    • If the divisor is 0, the log information is logged in the console, and the log information is recorded in the file, including the complete exception stack information.

JavaSE-14 Exception Handling

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.