Como lidar com NumberFormatException

Feb 22 2023
· O que é uma exceção?· NumberFormatException ∘ Hierarquia ∘ Sintaxe ∘ O que causa NumberFormatException ∘ Como lidar com NumberFormatException· Exemplos para implementar NumberFormatException em Java ∘ Exemplo #1 ∘ Exemplo #2· Evitar NumberFormatException O que é uma exceção? O NumberFormatException é uma exceção não verificada em Java que ocorre quando é feita uma tentativa de converter uma string com um formato incorreto em um valor numérico. O NumberFormatException é uma classe interna em java definida no Java.
origem

· O que é uma exceção?
· NumberFormatException
∘ Hierarquia
∘ Sintaxe
∘ O que causa NumberFormatException
∘ Como lidar com NumberFormatException
· Exemplos para implementar NumberFormatException em Java
∘ Exemplo #1
∘ Exemplo #2
· Evite NumberFormatException

O que é uma exceção?

  • Em seu sentido mais geral, uma exceção é um problema que aparece em tempo de execução que não pode ser antecipado por um programa Java geral e precisa ser especialmente tratado pelo programador.
  • Tipos comuns de exceção: FileNotFoundException , ClassNotFoundException , IndexOutOfBoundsException

O NumberFormatException é uma exceção não verificada em Java que ocorre quando é feita uma tentativa de converter uma string com um formato incorreto em um valor numérico.

O NumberFormatException é uma classe integrada em java definida no pacote Java.lang.NumberFormatException . A classe IllegalArgumentException é uma superclasse da NumberFormatException , pois é uma exceção não verificada, portanto não é forçada a tratá-la e declará-la.

Em um programa Java, às vezes a entrada do usuário é aceita por meio de argumentos de linha de comando como um campo de texto na forma de uma string. E para usar essa string em algumas operações aritméticas, ela deve primeiro analisar ou converter em tipos de dados (tipo numérico específico) usando as funções parseXXX() das classes wrapper

NumberFormatException é lançada quando não é possível converter uma string para um tipo numérico (por exemplo, int, float), porque o formato de uma string de entrada é ilegal e não apropriado. Por exemplo, esta exceção ocorre se uma string é tentada a ser analisada para um número inteiro, mas a string contém um valor booleano.

Hierarquia

A hierarquia da classe NumberFormatException é:

Object ->Throwable -> Exception ->RuntimeException ->NumberFormatException

Sintaxe

A seguir está a declaração para a classe java.lang.NumberFormatException .

public class NumberFormatException extends IllegalArgumentException implements Serializable
{
// Constructors of the NumberFormatException class
}

IllegalArgumentException class and implements Serializabletion.

A NumberFormatException ocorre quando é feita uma tentativa de converter uma string com formato impróprio em um valor numérico . Ou seja, quando não é possível converter uma string em qualquer tipo numérico (float, int, etc), esta exceção é lançada. É uma Runtime Exception (Unchecked Exception) em Java. É uma subclasse da classe IllegalArgumentException . Para lidar com essa exceção, o bloco try – catch pode ser usado.

Ao operar com strings, há momentos em que precisamos converter um número representado como uma string em um tipo numérico. O método geralmente usado para converter String para Integer em Java é parseXXXX() .

A NumberFormatException pode ser lançada por muitos métodos/construtores nas classes do pacote java.lang . A seguir estão alguns deles.

  • public static int parseInt(String s) lança NumberFormatException
  • public static Byte valueOf(String s) lança NumberFormatException
  • byte estático público parseByte(String s) lança NumberFormatException
  • byte estático público parseByte(String s, int radix) lança NumberFormatException
  • public Integer(String s) lança NumberFormatException
  • public Byte(String s) lança NumberFormatException

vamos pegar parseInt() como exemplo

Uso do método parseInt() : Como já sabemos, existem duas variantes deste método, a saber, para obter uma melhor compreensão

public static int parseInt(String s) throws NumberFormatException
This function parses the string argument as a signed decimal integer.
public static int parseInt(String s, int radix) throws NumberFormatException
This function parses the string argument as a 
signed integer in the radix specified by the second argument.

Construtores:

  1. public NumberFormatException(): Constrói um NumberFormatException sem nenhuma mensagem de detalhe.
  2. public NumberFormatException(String msg): Constrói um NumberFormatException com a mensagem de detalhe 'msg'
  • A string s é nula ou o comprimento de s é zero.
  • Se a String s contiver caracteres não numéricos.
  • O valor de String s não representa um inteiro.

Integer.parseInt("null") ;

Float.parseFloat(“”) ;

Vejamos uma tentativa de construir um objeto Integer ou Double com dados não numéricos.

Ambas as instruções lançarão NumberFormatException :

Integer aIntegerObj = new Integer("one");
Double doubleDecimalObj = new Double("two.2");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Exception in thread "main" java.lang.NumberFormatException: For input string: "one"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.<init>(Integer.java:867)
	at MainClass.main(MainClass.java:11)"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

A Java Number API não transforma palavras em números, então podemos corrigir o código simplesmente alterando-o para um valor esperado:

Integer aIntegerObj = new Integer("1");
Double doubleDecimalObj = new Double("2.2");

Semelhante ao suporte do Java para análise no construtor, temos métodos de análise dedicados como parseInt(), parseDouble(), valueOf() e decode().

Se tentarmos fazer os mesmos tipos de conversão com estes:

int aIntPrim = Integer.parseInt("two");
double aDoublePrim = Double.parseDouble("two.two");
Integer aIntObj = Integer.valueOf("three");
Long decodedLong = Long.decode("64403L");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

E podemos corrigi-los de maneiras semelhantes:

int aIntPrim = Integer.parseInt("2");
double aDoublePrim = Double.parseDouble("2.2");
Integer aIntObj = Integer.valueOf("3");
Long decodedLong = Long.decode("64403");

Double.parseDouble(“ThirtyFour”);

Integer.valueOf(“31.two”);

Ou, se tentarmos converter uma string em um número com dados estranhos na entrada, como espaços em branco ou caracteres especiais:

Short shortInt = new Short("2 ");
int bIntPrim = Integer.parseInt("_6000");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Poderíamos corrigi-los com um pouco de manipulação de string:

Short shortInt = new Short("2 ".trim());
int bIntPrim = Integer.parseInt("_6000".replaceAll("_", ""));
int bIntPrim = Integer.parseInt("-6000");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

A string de entrada com espaços em branco iniciais e/ou finais

Integer abc=new Integer(“  432 “);

Float.parseFloat(4-236);
Float.parseFloat(4,236);
Float.parseFloat(56*);

Vejamos um caso especial de números específicos de localidade. Nas regiões europeias, uma vírgula pode representar uma casa decimal. Por exemplo, “4000,1” pode representar o número decimal “4000,1”.

Por padrão, obteremos NumberFormatException tentando analisar um valor contendo uma vírgula:

double aDoublePrim = Double.parseDouble("4000,1");"); background-repeat: no-repeat; background-position: center center; background-color: rgb(99, 177, 117);">Copy

Podemos permitir vírgulas para a região europeia e evitar a exceção usando NumberFormat .

Vamos vê-lo em ação usando o Locale for France como exemplo:

NumberFormat numberFormat = NumberFormat.getInstance(Locale.FRANCE);
Number parsedNumber = numberFormat.parse("4000,1");
assertEquals(4000.1, parsedNumber.doubleValue());
assertEquals(4000, parsedNumber.intValue());

Integer.parseInt(“1326589741236”);

Integer.parseInt("13.26");

public class NumberFormatExceptionTest {
   public static void main(String[] args){
      int x = Integer.parseInt("30k");
      System.out.println(x);
   }
}

Exception in thread "main" java.lang.NumberFormatException: For input string: "30k"
       at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
       at java.lang.Integer.parseInt(Integer.java:580)
       at java.lang.Integer.parseInt(Integer.java:615)
       at NumberFormatExceptionTest.main(NumberFormatExceptionTest.java:3)

Podemos lidar com o NumberFormatException de duas maneiras

  • Use o bloco try e catch ao redor do código que pode causar NumberFormatException .
  • Outra maneira de lidar com a exceção é o uso da palavra-chave throws .

public class NumberFormatExceptionHandlingTest {
   public static void main(String[] args) {
      try {
         new NumberFormatExceptionHandlingTest().intParsingMethod();
      } catch (NumberFormatException e) {
         System.out.println("We can catch the NumberFormatException");
      }
   }
   public void intParsingMethod() throws NumberFormatException{
      int x = Integer.parseInt("30k");
      System.out.println(x);
   }
}

Saída

We can catch the NumberFormatException

Seguem exemplos de implementação:

Exemplo 1

A seguir, escrevemos o código java para entender mais claramente o NumberFormatException com o seguinte exemplo onde criamos um objeto PrintWriter usando o construtor da classe PrintWriter e passamos o nome do arquivo para escrever nele, conforme abaixo –

Código:

//package p1;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg) {
int age;
Scanner sc = new Scanner(System.in);
System.out.println("Please Enter your age : ");
//throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric.
age = Integer.parseInt(sc.next());
System.out.println("Your age is : " +age);
}
}

Quando o usuário insere “25+”, uma saída do código acima é:

Please Enter your age: 25+
Exception in thread "main" java.lang.NumberFormatException: For input string: "25+" 
    at java.lang.NumberFormatException.for InputString (NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615) 
    at Main.main (Main.java:11)

Please Enter your age: 25F 
Exception in thread "main" java.lang.NumberFormatException: For input string: "25F"
    at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615) 
    at Main.main (Main.java:11)

Please Enter your age: Twenty Five 
Exception in thread "main" java.lang.NumberFormatException: For input string: "Twenty" 
    at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615) 
    at Main.main (Main.java:11)

Please Enter your age: null
Exception in thread "main" java.lang.NumberFormatException: For input string: "null"
    at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615) 
    at Main.main (Main.java:11)

Please Enter your age: 25.5
Exception in thread "main" java.lang.NumberFormatException: For input string: "25.5"
    at java.lang.NumberFormatException.forInputString (NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615) 
    at Main.main (Main.java:11)

Please Enter your age: 25 :
25
Your age is 25

Exemplo #2

Em seguida, escrevemos o código java para entender o NumberFormatException onde geramos o NumberFormatException e o tratamos usando o bloco try-catch no programa, conforme abaixo –

Código:

//package p1;
import java.util.Scanner;
public class Demo
{
public static void main( String[] arg) {
int age;
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Please Enter your age : ");
//throws Exception as if the input string is of illegal format for parsing as it as null or alphanumeric.
age = Integer.parseInt(sc.next());
System.out.println("Your age is : " +age);
} catch(NumberFormatException e)
{
System.out.println("The NumberFormatException occure.");
System.out.println("Please enter the valid age.");
}
}
}

Please Enter your age :
23F
The NumberFormatException occure.
Please enter the valid age.

Please Enter your age :
23
Your age is 23

Evite NumberFormatException

Vamos falar sobre algumas boas práticas que podem nos ajudar a lidar com NumberFormatException :

  1. Não tente converter caracteres alfabéticos ou especiais em números — a API Java Number não pode fazer isso.
  2. Podemos querer validar uma string de entrada usando expressões regulares e lançar a exceção para os caracteres inválidos .
  3. Podemos limpar a entrada contra problemas conhecidos previsíveis com métodos como trim() e replaceAll() .
  4. Em alguns casos, caracteres especiais na entrada podem ser válidos. Então, fazemos um processamento especial para isso, usando o NumberFormat, por exemplo, que suporta vários formatos .

É uma prática recomendada verificar se a string passada é numérica ou não antes de tentar convertê-la em número inteiro.

Obrigado pela leitura.Bom aprendizado

Junte-se ao Grupo Mouad Oumous Java WhatsApp PARTICIPE

Junte-se ao canal de telegrama Mouad Oumous PARTICIPE

Apoie nossa publicação seguindo-a

Consulte também os seguintes artigos

Java — 8 | Interface BiFunction, BiConsumer e BiPredicate com exemplo Quem está moldando o futuro global da energia? 3 fatos que você não sabia sobre London Dicas para o console JavaScript aumentar sua capacidade de depuração