Force jump to catch

5

Is there any way to force the jump, without causing an exception, from inside try to catch ? For example:

try {

    // Código
    // ...
    //

    //Provocar salto al "catch" -> ¿otra opción?
    Integer.parseInt( "hola" );

} catch( Exception e ) {

    // Código
    // ...
    //
}

What I'm trying to do is the following:

The program requests the selection of an option number, say from 1 to 5. As I expect a number, I do a conversion to int type of the entry within the try, if it fails, I show a message and call recursively to the function, until you get a valid number. Out of the try-catch (I already have a number), I check that the number is within an interval, otherwise, again I show a message and recursive call ... what I wanted was to put this check in the try, after of the conversion and jump to the catch if the number was not among the expected, to save a few lines. What I have works, but I want to improve it.

So what I want to know is how to force a jump into the catch without forcing an exception, if there is any way predicted.

    
asked by Orici 19.12.2016 в 20:02
source

10 answers

5
  

Is there any way to force the jump, without causing an exception, from the inside of try to catch ?

You can not force the execution of the catch if you have not launched a Throwable , that is, an exception or an error, within the try section.

This is explained very well in the JLS 14 Blocks and Statements 14.20. The try statement 14.20.1. Execution of try-catch and 14.20. two. Execution of try-finally and try-catch-finally

    
answered by 19.12.2016 в 20:40
4

For this case I would recommend that you create your own exceptions by extending the class Exception in the following way:

public class ExcepcionPropia extends Exception {
    public ExcepcionPropia(String mensaje) {
        super(mensaje);
    }
}

leaving your code as follows:

try{
     if (numEntrada == valor) {
          throw new ExcepcionPropia();
     }
}catch(ExcepcionPropia e){
     // Aqui recoges la excepcion que has forzado
}catch(Excepcion e){
     // Aqui se recogen las demás excepciones
}

where you can end the try-catch when it is not satisfied that the entry number is equal to the desired value, thus launching the own exception and collecting it in the corresponding catch block, executing the desired actions within this block .

    
answered by 20.12.2016 в 01:10
4

Good morning.

You can launch an exception from anywhere in the program, regardless of whether it is captured for a catch . To do this you must create the exception and throw it with the reserved word throw in the following way:

throw new EmptyStackException();

This will cause the block catch with the type of the appropriate exception to be executed. To do this, it looks for the stack of calls to the block that can capture it, if there is not, the virtual machine will end the execution of the program when it fails to process the error (propagation of exceptions , What is exception propagation ? ).

Consider the following image:

You can launch with thow any class that is Throwable's daughter. If you want to throw an exception of type Exception but do not want to process it you must declare in the function where the excemption is given that must be captured in a higher level (this is not necessary for children of RuntimeException ), this is from the < a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html"> following way :

public void FuncionQueNoProcesaExcepciones throws Exception, 
                                                  MiException {
    // ...
}

Now if you want to capture an exception, the structure of an exception handler contains the reserved words try , catch , finally . The structure is as follows:

try {
    // codigo que podría lanzar excepciones. Puedes ser distintos
    // tipos como IOException, IndexOutOfBoundsException
} catch (IOException excepcion){
    // Este bloque solo se ejecuta cuando se lanza una excepcion 
    // del tipo IOException
} catch (IndexOutOfBoundsException excepcion){
    // Este bloque solo se ejecuta cuando se lanza una excepcion 
    // del tipo IndexOutOfBoundsException
} finally {
    // siempre se llama a finally, haya una excepcion o no.
}

Clarifying the function of the try-catch block, responding to:

  

Is there any way to force the jump, without causing an exception, from inside the try to the catch?

Here are the options:

  • Use throw to execute the catch . This takes you out of the normal flow of the program.
  • Use a method in catch , so that it can be called without throwing an exception. This way you can call it from anywhere, even within the try (obvious is a method).

    public static void main(String[] args) {
        String texto = "Desde el try";
        try {
            // codigo
            procesaExcepcion(texto);
    
            // si se llamara desde el catch ...
            throw new Exception();
        } catch (Exception c) {
            texto = "Desde el catch";
            procesaExcepcion(texto, c);
        }
    }
    
    public static void procesaExcepcion(Object... contexto) {
        // hacer cosas para procesar la excepcion
        System.out.println(contexto[0]);
    }
    
  • Use reflection functions and frameworks to manipulate bytecodes (this is the only way to run catch without throwing an exception), but this is not easy at all.

Now, your problem does not need a recursive call

  

"I show a message and recursively call the function"

The correct way to validate an entry is by using the do-while cycle, as follows

java.util.Scanner sc = new java.util.Scanner(System.in);
int variable = -1;

do {
    try {
        System.out.print("Ingrese una opcion: ");
        variable = Integer.parseInt( sc.nextLine() );
    } catch( NumberFormatException e ) {
        // no es necesario poner algo aqui
    }
} while (variable < 1 || variable > 5);

System.out.print(variable);

The above code declares and initializes a variable that stores the number you wish to validate. When trying to convert with parseInt there are two options: convert or throw an exception.

  • If it is converted, the while of the cycle validates that it is among the desired values, if not, the entry is read again.
  • In case of exception, the variable is -1, so it is not a valid value and the cycle is repeated.

Now, if you want a shorter code you can change the block:

try {
        System.out.print("Ingrese una opcion: ");
        variable = Integer.parseInt( sc.nextLine() );
} catch( NumberFormatException e ) {
        // no es necesario poner algo aqui
}

for

while (!sc.hasNextInt()) sc.next();
variable = sc.nextInt();

Finally if you have problems with the lines;) you can always write everything in one without spaces:

Scanner s=new Scanner(System.in);
int v=-1;do{while(!s.hasNextInt())s.next();v=s.nextInt();}while(v<1||v>5);
    
answered by 20.12.2016 в 17:39
1

The try ... catch

function

In the try part is a section of code where the statement (s) will try to capture a possible error. If it occurs, it must be captured where the catch part appears. Example:

try{
     // Instrucciones que se intentan ejecutar, Si se produce una
     // situación inesperada se lanza una excepción.
}catch(tipoExcepcion e){
     // Instrucciones para tratar esta excepción.
}catch(otroTipoExcepcion e){
     // Instrucciones para tratar esta excepción.
}

If you want to force the error, because the number was entered incorrectly, you do not need to be inside a try ... catch. The try catch function is not worth using for this case. You could add an if to see that it does not meet the expected value and display a message indicating that.

Example:

if(numero >= 6){
    System.out.println("Numero incorrecto!!!");
}
    
answered by 20.12.2016 в 01:01
0

The end of a try-catch is this, if what is intended is that nothing be done if it is the case then simply leave it empty:

try{
}catch(SomeException e){}

Although in my opinion it is not recommended since in such case of having an unexpected behavior, these exceptions are those that help us to debug the code.

If you want to skip a catch ONLY in a particular case, something similar to a break xyz; for an iteration, that is not possible.

    
answered by 19.12.2016 в 20:11
0

You can throw an exception with

  

throw new Exception ();   But it seems to me that the best thing is that you do a method with what you need to do in the failure, or a method to know what to do in the try, this to improve the reading.

try {

    // Código
    // ...
    //

    //Provocar salto al "catch" -> ¿otra opción?
   int valor= Integer.parseInt( tuCadenaConNumero );
   if(valor<1 || valor> 5)
      mandarErrorYRegresar(tuCadenaConNumero );

} catch( Exception e ) {
    mandarErrorYRegresar(tuCadenaConNumero );
    // Código
    // ...
    //
}

[...]

public void mandarErrorYRegresar(String tuCadenaConNumero ){
   System.out.println("El valor '"+tuCadenaConNumero +"' No es valido");
   //codigo para volver a pedir el numero;
   PedirNumero();
}

or within the try call a function that does all the validations, this function sends exception when something is not within the necessary

    
answered by 20.12.2016 в 17:45
0
  

Is there any way to force the jump, without causing an exception,   from the inside of the try to the catch?

Precisely the catch is created to capture an exception type, if you do not generate an error you will not force the jump to the block catch :

try {

    // Código
    // ...
    //

    //Provocar salto al "catch" -> ¿otra opción?
    Integer.parseInt( "hola" );

} catch( Exception e ) {

    // Código
    // ...
    //
}

Instead you can throw an exception creating your exception:

public class MyCustomExcepcion extends Exception{

    public MyCustomExcepcion(String excute)
    {
        super(excute);
    }
    public String getMessage()
    {
        return super.getMessage();
    }
}

Which would you use in this way:

 MyCustomExcepcion myCustomException = new MyCustomExcepcion("mi error personalizado.");

    try {    
        ...
        ...
        ...    
        //Provocar salto al "catch" -> ¿otra opción?
        //Integer.parseInt( "hola" );
        //Esta sería la opción:
        throw myCustomExcepcion();

    } catch(MyCustomExcepcion e) {    
       ...
       ...          
    } catch(Exception e) {    
       ...
       ...
    }
    
answered by 22.12.2016 в 18:42
0

Based on what you write that you want to do, it occurred to me to solve it in the following way:

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Scanner;  // needed for Scanner

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        FnConTry();
    }

    public static void FnConTry(){
        try {

            // Codigo
            // ...
            //
            //Solicito un numero
            // 1. Create a Scanner using the InputStream available.
            Scanner scanner = new Scanner( System.in );
            // 2. Don't forget to prompt the user
            System.out.print( "Escribe un numero: " );
            // 3. Use the Scanner to read a line of text from the user.
            String n = scanner.nextLine();
            int numero = 0;

            //Provocar salto al "catch" -> otra opcion?
            numero = Integer.parseInt( n );
             if(numero >= 1 && numero <= 5){
                System.out.println("Numero Valido");
            }
            else{
                System.out.println("El numero no esta en el rango!!");
                FnConTry();
            }

        } catch( Exception e ) {

            System.out.println("\nRecuerde que debe introducir un numero");
            FnConTry();
            // Codigo
            // ...
            //
        }
    }
}

What you say to send to catch without throwing an exception, I do not find sense, I do not know if you want to save resources or something ... if you can find out how to do it please share the answer.

    
answered by 22.12.2016 в 20:12
0

You can execute force by firing an exception or execute instructions with finally

public static void main(String[] args) {
        try{
            throw new NumberFormatException("Error formato del numero");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            System.out.println("Algo finalmente");
        }
    }
    
answered by 25.12.2016 в 16:58
-1

Well as you mentioned above, you can do a throw new RuntimeException("Mensaje") in try and that will send it directly to the catch

I give you a clearer example of how to do it directly

try {

    // Código
    // ...
    //

    If(<<condicion>>)
    {
        throw new RuntimeException("No me gusta este número")
    }
    Integer.parseInt( "hola" );

} catch( Exception e ) {

    // Código
    // ...
    //
}
    
answered by 20.12.2016 в 20:19