<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NumberFormatException &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/numberformatexception/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Fri, 27 May 2022 11:32:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>7 different ways how to get NumberFormatException in Java</title>
		<link>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/</link>
					<comments>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 05 May 2022 11:30:51 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[NumberFormatException]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1304</guid>

					<description><![CDATA[This article will show you the NumberFormatException, how you are getting it and what you should do to handle the exception properly. <a href="https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>If you get NumberFormatException in Java, it is highly probable because of the following reasons. This article will uncover the NumberFormatException, how you are getting it and what you should do to handle the exception properly.</p>
<p><span id="more-1304"></span></p>
<h2>What is NumberFormatException</h2>
<p>The NumberFormatException is an unchecked Java exception which happens when there is incorrect string input converted to a numeric value. When the input is wrong, NumberFormatException is thrown to inform the user that the conversion requires a correct input and the transformation did not happen. For example, the NumberFormatException is thrown when a numerical string is parsed to an integer, but the string contains also space.</p>
<p>As the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. However, when in doubt of input correctness, it should be handled in code using a try-catch block.</p>
<h2>NumberFormatException Example</h2>
<p>Let&#8217;s take a look at the simple example of NumberFormatException being thrown:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int orderNumber = Integer.parseInt("Order 66");
        System.out.println(orderNumber);
    }
}</code></pre>
<p>The above code will throw NumberFormatException. While pure input of string &#8220;66&#8221; is a valid input, a string with non-numerical characters like &#8220;Order 66&#8221; is unsuitable for creating a number.</p>
<pre><code class="language-java">Exception in thread "main" java.lang.NumberFormatException: For input string: "Order 66"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:6)</code></pre>
<h2>8 Different Ways How To Get NumberFormatException</h2>
<p>There are various causes for throwing NumberFormatException, and the improper conversion of invalid input mainly causes them. Here is a list of different ways how to get NumberFormatException:</p>
<p>1. Input string is empty:</p>
<pre><code class="language-java">Integer.parseInt("");</code></pre>
<p>2. Input string is null:</p>
<pre><code class="language-java">Integer.parseInt(null);</code></pre>
<p>3. Input string with non-numeric data:</p>
<p>This case has several different options why it can happen.</p>
<p>a. Input string contains space character:</p>
<pre><code class="language-java">Integer.parseInt("66 66");</code></pre>
<p>b. Input string contains non-numeric character:</p>
<pre><code class="language-java">Integer.parseInt("Sixty");</code></pre>
<p>c. Numeric input with non-numeric character in input string</p>
<pre><code class="language-java">Integer.parseInt("Catch22");</code></pre>
<p>4. Input string with inappropriate symbols in it:</p>
<pre><code class="language-java">Double.parseDouble("66,12345");</code></pre>
<p>5. Input string with leading or tailing white space</p>
<pre><code class="language-java">Integer randomExample = new Integer("  12345  ");</code></pre>
<p><em>Integer</em>, <em>Long</em>, <em>Short</em>, <em>Byte</em> throw NumberFormatException; <em>Double</em>, <em>Float</em> does not.</p>
<p>6. Mismatch of data type between input string and the target data type</p>
<pre><code class="language-java">Integer.parseInt("12.34");</code></pre>
<p>7. Input string exceeding the range of the target data type</p>
<pre><code class="language-java">Integer.parseInt("2147483648");</code></pre>
<p>The example shown above is a case of NumberFormatException upon placing a numeric input string exceeding the range of the target data type, which is in our case <em>Integer</em> class object. The maximum range for Integer class object is from -2_147_483_648 to 2_147_483_647.</p>
<h2>How to handle NumberFormatException</h2>
<p>The NumberFormatException is an unchecked exception in Java. Therefore it can be handled as any other Java exception by wrapping critical code to try-catch block.</p>
<p>Look at the following example of catching NumberFormatException with a try-catch block:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {

    public static void main(String args[]) {
        String userInput = "Order 66";
        Optional&lt;Integer&gt; orderNumber = processOrder(userInput);
        if (orderNumber.isPresent()) {
            System.out.println("Execute order " + orderNumber.get());
        } else {
            System.out.println("Unrecognized order number. Please try again.");
        }
    }

    public static Optional&lt;Integer&gt; processOrder(String userInput) {
        try {
            int order = Integer.parseInt(userInput);
            return Optional.of(order);
        } catch (NumberFormatException ex) {
            System.out.println("Order exception: Invalid user input!");
        }
        return Optional.empty();
    }

}</code></pre>
<p>Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message or return an empty Optional object if you are using at least Java 8. Like in the example above, wrapping the code in try-catch blocks allows the program to continue execution after the code throws the exception.</p>
<p><b>Output</b>:</p>
<pre><code class="language-bash">Order exception: Invalid user input!
Unrecognized order number. Please try again.</code></pre>
<h2>Conclusion</h2>
<p>This article led us to explain what NumberFormatException and how to handle it. It also showed over seven different ways how the NumberFormatException can occur and how we can defensively take care of it.</p>
<p>Do you know NumberFormatException? In what case did it throw to you? Do you have your trick, or do you see another way <u>how to handle NumberFormatException</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
