What is the try and catch for? in java

0

In the following code that function exerts the try and catch class?

package Package;
import java.io.*;

public class Textos {

    public void leer (String nombreArchive) {
        try {

            FileReader r= new FileReader (nombreArchive);
            BufferedReader buffer = new BufferedReader (r);
            //System.out.println(buffer.readLine());

            String temp="";
            while(temp!=null) {
                temp = buffer.readLine();
                if (temp==null)
                    break;
                System.out.println(temp);
            }
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }       
    }
}
    
asked by Redes del Hack 21.08.2017 в 06:21
source

2 answers

7

The try catch in programming is used to handle code fragments that are prone to fail, such as: receive a null value, convert one type of data to another or in your case, reading a file.

When reading a file that is stored in the memory of the device (internal or external), a bit stream (physically current) is generated from said memory to the RAM memory. That flow can be interrupted for different reasons, which would cause the task to fail and the program to stop. The try catch what it does is make sure that even if the task that is running fails, the program continues executing and does not stop.

If the code that is inside the try fails, the catch is executed and the program is still running. Inside the try you must place the code that is prone to fail and within the catch the code to be executed if the try fails, such as an error message.

The try catch should be used when you have a fragment of code that is prone to fail, which is known to fail for one reason or another. As for example the conversion of one type of data to another:

try {

    // Convierte un valor de tipo String a int
    int numero = Integer.parseInt("a456");

} catch(Exception e) {

    System.out.println("ERROR: el valor de tipo String contiene caracteres no numéricos");

}

In this case the code that is inside the try would fail and the code that is inside the catch would be executed. If the try catch is not used in this case, the program would stop when the error occurs. But when using try catch, even if the error occurs, the program will continue to run normally.

    
answered by 21.08.2017 в 07:23
1

Try = Try, catch = catch,

Basically in the code segment within the try will be the process that will try to follow your program and in case of an error, exception or failure for some reason, then catch catch said error or Exception in variable e ( e is only the variable name is not mandatory to always call it that way but if it is advised).

  

Note : I believe that in any programming language the functionality is the same

    
answered by 21.08.2017 в 07:39