Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java exception handling mechanism     - Simple to use multi-threaded programming under Linux mutex and condition variable (Programming)

- Using shell users or virtual users to login to pureftpd (Linux)

- Profile Linux users login shell and login to read (Linux)

- Windows 8.1 and Ubuntu 14.04 dual system uninstall Ubuntu Tutorial (Linux)

- Spring-depth understanding of the various annotations (Programming)

- C ++ implementation of the list of basic operations and test cases (Programming)

- Nginx + ownCloud + PHP + MySQL to build personal private cloud under CentOS7 (Server)

- Linux Powerful command Awk Introduction (Linux)

- How to display a dialog Bash Shell script (Programming)

- 64-bit Oracle Linux recompiled Hadoop-2.2.0 (Server)

- Linux SU command security Suggestions (Linux)

- GitLab Installation Guide -Ubuntu 14.04 LTS (Server)

- Ubuntu 15.04 / CentOS 7.0 to set custom boot (Linux)

- How to install Unbound and DNSCrypt in Archlinux (Server)

- Oracle 10046 Event (Database)

- ORA-00824: can not set sga_target due to existing problem-solving (Database)

- MongoDB upgrade from 2.4.9 to 2.6.0 and PHP record of mongo extension upgrade from 1.4.5 to 1.5.1 (Database)

- Embedded Linux Optimization (Programming)

- Macro Analysis Performance: PHP Performance Analysis and Experiment (Programming)

- Install Ubuntu Software Center App Grid (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:      
 
- After SSH change the default port, how to use Git (Linux)
- Understanding the type in C ++ bitset (Programming)
- ActiveMQ configuration Getting Started Tutorial (Server)
- MySQL uses Federate engine mapping table to achieve operation of the local remote operation table (Database)
- To share Linux script automatically change passwords (Linux)
- Customize the output format in Linux history (Linux)
- Using Ruby to build a simple HTTP service and sass environment (Server)
- Sublime Text 3 practical functions and shortcut keys used to collect (Linux)
- How to use the Vault secure password storage and API key (Linux)
- Automatic and Manual Proxy Settings Switch GNOME Shell Extension Proxy Switcher Recommend (Linux)
- The best tools and techniques to find data on a Unix system (Linux)
- Git delete files (Linux)
- CentOS 6/7 Series Docker Installation (Linux)
- Detailed installation of CentOS 6.x (Linux)
- C language preprocessor command (Programming)
- Linux System Getting Started Tutorial: Installing Brother printer in Linux (Linux)
- Postgres-X2 deployment steps (Database)
- Hadoop 1 and 2.x installation notes (Server)
- Bash common several configuration files (Linux)
- Linux Basics Tutorial: create your own Vim IDE (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.