Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java exception handling mechanism     - CentOS7 installation performance monitoring system (Server)

- Linux System Getting Started Learning: After starting in Ubuntu or Debian, enter the command line (Linux)

- Linux Routine Task Scheduler (Linux)

- SUSE Linux firewall configuration notes (Linux)

- How to understand Python yield keyword (Programming)

- Quick Install software RAID on Linux (Linux)

- Install Java, Maven, Tomcat under Linux (Linux)

- Linux Network Programming - raw socket can do (Programming)

- Let the terminal under Mac OS X as like Linux has displayed a variety of colors (Linux)

- Analysis JavaBean (Programming)

- How to use Aptik to backup and restore Apps/PPAs under ubuntu (Linux)

- PHP generates a random password several ways (Programming)

- HTML5 postMessage cross-domain data exchange (Programming)

- JavaScript is implemented without new keywords constructor (Programming)

- Open log in Hibernate (Programming)

- IPTABLES configuration steps under Linux (Linux)

- MySQL and Oracle time zone settings compare (Database)

- Python regular expressions: how to use regular expressions (Programming)

- How to manage your to-do list with the Go For It on Ubuntu (Linux)

- tar command to extract a file error: stdin has more than one entry (Linux)

 
         
  Java exception handling mechanism
     
  Add Date : 2017-08-31      
         
         
         
  1. How to catch exceptions

try

{

Snippet may appear abnormal;

}

catch (exception handling the exception object type name)

{

Exception handling code segment;

}

import java.io. *;

public class TryCatchTest {

    public static void main (String [] args) {
        File file = new File ( "abc.txt");
        int a [] = {1, 2};
        
        try
        {
            System.out.println (3/0);
        }
        catch (ArithmeticException e1)
        {
            System.out.println ( "3/0:");
            System.out.println ( "This is ArithmeticException");
        }
        
        try
        {
            System.out.println (a [2]);
        }
        catch (ArrayIndexOutOfBoundsException e2)
        {
            System.out.println ( "a [2] is out of Array:");
            System.out.println ( "This is ArrayIndexOutOfBoundsException");
        }
        
        try
        {
            BufferedReader input = new BufferedReader (new FileReader (file));
        }
        catch (FileNotFoundException e3)
        {
            System.out.println ( "abc.txt is not found:");
            System.out.println ( "This is FileNotFoundException");
        }
        catch (IOException e)
        {
            System.out.println ( "This is IOException");
        }

    }

}

3/0:
This is ArithmeticException
a [2] is out of Array:
This is ArrayIndexOutOfBoundsException
abc.txt is not found:
This is FileNotFoundException

 

2. How to throw an exception

Coding process, if you do not want to capture and handle an exception that may occur in this code, we need to pass out this anomaly, it is passed to the calling method to handle the exception. This time you need to use throw and throws
throws statement in the method used in the declaration, an exception is thrown
throw statement in the body of the method used internally thrown

Note: If you use the method body throw statement to throw an exception, you must declare the method, using throws statement to declare the exceptions thrown by the method body, simultaneously, throws statement declares thrown exception must be a method body the throw statement throws an exception or parent class of the exception.

import java.io. *;

public class ThrowTest {
    
    public void throwTest1 () throws ArithmeticException
    {
        System.out.println (3/0);
    }
    
    public void throwTest2 () throws ArrayIndexOutOfBoundsException
    {
        int a [] = {1,2};
        System.out.println (a [2]);
    }
    
    public void throwTest3 () throws FileNotFoundException
    {
        File file = new File ( "abc.txt");
        new BufferedReader (new FileReader (file));
    }
    
    public void throwTest4 () throws FileNotFoundException
    {
        throw new FileNotFoundException ( "abc.txt");
    }

    public static void main (String [] args) {
        ThrowTest throwTest = new ThrowTest ();
        
        try
        {
            throwTest.throwTest1 ();
        }
        catch (ArithmeticException e1)
        {
            System.out.println ( "3/0:");
            System.out.println ( "This is ArithmeticException");
        }
        
        try
        {
            throwTest.throwTest2 ();
        }
        catch (ArrayIndexOutOfBoundsException e2)
        {
            System.out.println ( "a [2] is out of Array:");
            System.out.println ( "This is ArrayIndexOutOfBoundsException");
        }
        
        try
        {
            throwTest.throwTest3 ();
        }
        catch (FileNotFoundException e3)
        {
            System.out.println ( "abc.txt is not found:");
            System.out.println ( "This is FileNotFoundException");
        }
        
        try
        {
            throwTest.throwTest4 ();
        }
        catch (FileNotFoundException e3)
        {
            System.out.println ( "abc.txt is not found:");
            System.out.println ( "This is FileNotFoundException");
        }

    }

}

3/0:
This is ArithmeticException
a [2] is out of Array:
This is ArrayIndexOutOfBoundsException
abc.txt is not found:
This is FileNotFoundException
abc.txt is not found:
This is FileNotFoundException

3. custom exception

Create your own exception classes needed to do was inherited from the subclass Exception class needs a class or classes from Exception. Traditionally, often for each exception class that provides a default constructor and contains detailed information. Note that the custom exception class, must be used by programmers throw statement.

public class MyException {

    public static void main (String [] args) {
        String str = "2abcde";
        
        try
        {
            char c = str.charAt (0);
            if (c < 'a' || c> 'z' || c < 'A' || c> 'Z')
                throw new FirstLetterException ();
        }
        catch (FirstLetterException e)
        {
            System.out.println ( "This is FirstLetterException");
        }

    }

}

class FirstLetterException extends Exception {
    public FirstLetterException ()
    {
        super ( "The first char is not a letter");
    }
    
    public FirstLetterException (String str)
    {
        super (str);
    }
}

This is FirstLetterException

public class MyException {

    public static void main (String [] args) throws FirstLetterException {
        throw new FirstLetterException ();
    }
}

class FirstLetterException extends Exception {
    public FirstLetterException ()
    {
        super ( "The first char is not a letter");
    }
    
    public FirstLetterException (String str)
    {
        super (str);
    }
}

Exception in thread "main" FirstLetterException: The first char is not a letter
 at MyException.main (MyException.java:5)

4. Use the finally statement

Using the try ... catch statement is, if the try statement a certain unusual circumstances, this part of the try statement block, the statement from the abnormal, all subsequent statements will not be executed until this part try end statement section.

But in many cases it is desirable regardless of whether there is an exception, certain statements need to be executed. Then you can put some code in the finally block statement, or even try catch statement contained in paragraph return statement, the program will be executed after the exception is thrown finally statement section, unless try or catch block contains the statement System.exit ( ) method, or an error occurred error, finally statement will not be executed and exit the program.

import java.io. *;

public class FinallyTest {

    public static void main (String [] args) {
        File file = null;
        BufferedReader input = null;
        file = new File ( "abc.txt");
        
        try
        {
            input = new BufferedReader (new FileReader (file));
        }
        catch (FileNotFoundException e)
        {
            System.out.print ( "abc.txt is not found:");
            System.out.println ( "This is FileNotFoundException");
        }
        finally
        {
            System.out.println ( "This is finally code part.");
        }

    }

}

abc.txt is not found: This is FileNotFoundException
This is finally code part.
     
         
         
         
  More:      
 
- Detailed driver compiled into the Linux kernel (Programming)
- Oracle archive log summary (Database)
- Linux system performance and usage activity monitoring tools -Sysstat (Linux)
- Flow control message transmission between RAC (Database)
- To install Google Chrome browser under Ubuntu 14.04 LTS (Linux)
- Workspace Go language and environment variables GOPATH (Linux)
- Install Ruby on Rails in Ubuntu 15.04 in (Linux)
- C ++ in the elimination Wunused (Programming)
- Linux file system management partition, format, mount - label mount (Linux)
- Oracle Character Set Summary (Database)
- Handle large data problems Bit-map method (Programming)
- Oracle 11g dataguard main library backup and recovery to the test environment in one database error (Database)
- Jigsaw project will solve the problem of Java JAR hell Mody (Programming)
- Oriented C ++ test-driven development (Programming)
- How to modify the Sublime in Tab four spaces (Linux)
- Linux terminal interface font color settings (Linux)
- Linux system on how to use rsync to synchronize data (Server)
- Ubuntu 14.04 LTS 64-bit installation and activation Sublime Text 3 can not solve the Chinese input method to solve the problem (Linux)
- Vim highlight lookup operation (Linux)
- Nginx high concurrency optimization ideas (Server)
     
           
     
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.