Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java exception handling mechanism     - Linux how to view the graphics models notebook (Linux)

- Linux command line to put on your coat GUI (Linux)

- Log device files under Linux - logger (Linux)

- How to build a container cluster (Server)

- Install apr support for Tomcat on Linux (Server)

- Ubuntu installation 2.10.x version of Scala (Linux)

- PL / SQL in forall simple test (Database)

- The principle Httpclient4.4 (execution request) (Programming)

- Android Launcher3 Application List Modify a transparent background (Linux)

- Linux terminal interface font color settings (Linux)

- An Example of GoldenGate Extract Process Hang Problem Solving (Database)

- Everyone should know something about TCP (Linux)

- Use PXE with kickstart to install Linux automatically (Linux)

- Getting Started with Linux: Learn how to install and access CentOS 7 Remote Desktop on a VPS (Server)

- Linux System Getting Started Learning: The Linux log (Linux)

- Oracle Linux 5.9 configuration Xmanager (Linux)

- The virtual memory (Linux)

- Different versions of MongoDB achieve master-slave replication (Database)

- Android Sets the system screen brightness (Programming)

- Install and use automated tools Ansible in CentOS 7 (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:      
 
- Reported too many open files Linux solutions (Server)
- systemd run levels and service management command Introduction (Linux)
- ARM runtime environment built from scratch using QEMU emulator (Linux)
- Linux System Getting Started Learning: install software packages on Ubuntu and Fedora (Linux)
- Distributed File System using MogileFS (Linux)
- Ubuntu the ARP (arptables) (Linux)
- RHEL (RedHat) 6.3 using EPEL Yum source (Linux)
- Ubuntu install Tonido private cloud services (Server)
- ASM learning overview (Database)
- MySQL loose index scan (Database)
- Ubuntu modify locale problem solving (Linux)
- CentOS 7 repair MBR and GRUB (Linux)
- How SSHfs mount a remote file system on Linux (Linux)
- Sleuth Kit: used to analyze a disk image and restore files open source forensics tools (Linux)
- MongoDB replication instance (Database)
- PostgreSQL Stream Configuration (Database)
- grep command Series: grep command to search for multiple words (Linux)
- MySQL common functions summary (Database)
- Linux kernel compilation, the configuration of the motor drive (Programming)
- Using IE can also be easily remotely control the computer (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.