Exception – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 11:58:14 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Exception – Java2Blog https://java2blog.com 32 32 [Fixed] IllegalArgumentException: Bound must be positive https://java2blog.com/illegalargumentexception-bound-must-be-positive/?utm_source=rss&utm_medium=rss&utm_campaign=illegalargumentexception-bound-must-be-positive https://java2blog.com/illegalargumentexception-bound-must-be-positive/#respond Sat, 17 Sep 2022 18:37:33 +0000 https://java2blog.com/?p=20589 In this post, we will see how to fix IllegalArgumentException: Bound must be positive in java.

You will generally get this exception while generating random numbers using Random.nextInt() method. If you pass bound as 0 or less than 0, then you will get the exception.

Let’s understand with the help of example:

package org.arpit.java2blog;

import java.util.Random;

public class GenerateRandomNumberMain {

    public static void main(String[] args) {
        System.out.println("============================");
        System.out.println("Generating random number");
        System.out.println("============================");
        Random randomGenerator=new Random();
        System.out.println(randomGenerator.nextInt(0) + 1);
    }
}

When you run the code, you will get following exception.

============================
Generating random number
============================
Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
    at java.base/java.util.Random.nextInt(Random.java:388)
    at org.arpit.java2blog.GenerateRandomNumberMain.main(GenerateRandomNumberMain.java:12)

As we have passed bound as 0 to nextInt(), we got above exception.

Here is source code Random’s nextInt() method.

public int nextInt(int bound) {
        if (bound <= 0)
            throw new IllegalArgumentException(BadBound);

        int r = next(31);
        int m = bound - 1;
        if ((bound & m) == 0)  // i.e., bound is a power of 2
            r = (int)((bound * (long)r) >> 31);
        else {
            for (int u = r;
                 u - (r = u % bound) + m < 0;
                 u = next(31))
                ;
        }
        return r;
    }

As you can see, if bound is less than or equals to 0, we will get this exception.

To resolve the issue, pass positive number to nextInt() method.

Here is code to generate random number between 1 to 5.

package org.arpit.java2blog;

import java.util.Random;

public class GenerateRandomNumberMain {

    public static void main(String[] args) {
        System.out.println("============================");
        System.out.println("Generating random number");
        System.out.println("============================");
        Random randomGenerator=new Random();
        System.out.println(randomGenerator.nextInt(5)+1);
    }
}

When you run the code, you will get following exception.

============================
Generating random number
============================
2

As you can see, we have passed bound as 5 to nextInt() method and it worked fine now.

That’s all about how to fix IllegalArgumentException: Bound must be positive.

]]>
https://java2blog.com/illegalargumentexception-bound-must-be-positive/feed/ 0
[Solved] Exception in thread “main” java.lang.NullPointerException https://java2blog.com/exception-thread-main-java-lang-nullpointerexception/?utm_source=rss&utm_medium=rss&utm_campaign=exception-thread-main-java-lang-nullpointerexception https://java2blog.com/exception-thread-main-java-lang-nullpointerexception/#respond Tue, 06 Apr 2021 14:00:13 +0000 https://java2blog.com/?p=6047 In this tutorial, we will see the most frequent java exception i.e. Exception in thread main java.lang.NullPointerException. It is one of the Runtime Exception.

Raise your hand if you ever got NullPointerException while working on java code. I am sure that this is the exception you might have encountered most frequently. You might also agree that NullPointerException is pain for most of java developers(novice or expert), but there is not much we can do about them, because this is the price we need to pay for convenient or unavoidable null references.

NullPointerException

Reasons for NullPointerException

Reasons for NullPointerException as defined by Java docs.

  • Invoking the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.
  • When you add null to Collections which do not allow nulls such as [ConcurrentHashMap](https://java2blog.com/concurrenthashmap-in-java/ “ConcurrentHashMap”)
  • Trying to synchronize using null object.

Let’s understand each of these in detail. I am creating a Employee class which we are going to use in our examples.

package org.arpit.java2blog;

public class Employee {
    String name;
    int age;

    public Employee()
    {

    }

    public Employee(String name, int age) {
        this.name=name;
        this.age=age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

1. Invoking the instance method of a null object

This is most obvious one.

package org.arpit.java2blog;
public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        Employee e1=null;
        String name = e1.getName();
        System.out.println("Employee Name: "+ name);
    }
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)

As you can see, e1 is null at line 7 and we are calling getMethod on it, thats why we are getting Exception in thread " main java.lang.NullPointerException here.

2. Accessing or modifying the field of a null object.

It is very much similar to calling instance method on null.

package org.arpit.java2blog;

public class NullFieldExampleMain {

    public static void main(String[] args) {
        Employee e1=null;
        String name = e1.name;
        System.out.println("Employee Name: "+ name);
    }

}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.NullFieldExampleMain.main(InvokingMethodOnNullMain.java:8)

As you can see, e1 is null at line 8 and we are accessing name field of e1, thats why we are getting NullPointerException here.

3. Taking the length of null as if it were an array.

When you try to get length of null array, you will get NullPointerException.

package org.arpit.java2blog;

public class NullArrayLengthMain {

    public static void main(String[] args) {
        Employee[] arrEmp=null;

        int length = arrEmp.length;
        System.out.println("Length of array: "+length);
    }
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.NullArrayLengthMain.main(InvokingMethodOnNullMain.java:9)

4. Accessing or modifying the slots of null as if it were an array.

When you try to access or modify null slot in array.Let’s understand with the help of example.

package org.arpit.java2blog;

public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        Employee[] arrEmp=null; 
        System.out.println(arrEmp[3]);
    }
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:8)

5. Throwing null as if it were a Throwable value.

When you throw null as Throwable.

package org.arpit.java2blog;

public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        throw null;
    }
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)

6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap

package org.arpit.java2blog;

import java.util.concurrent.ConcurrentHashMap;

public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>();
        map.put(null, "Dummy");
    }
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1022)
at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1017)
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)

7. Trying to synchronize using null object.

When you synchronize on null object, you will get NullPointerException

package org.arpit.java2blog;

import java.util.concurrent.ConcurrentHashMap;

public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        Object obj=null;
        synchronized (obj) {
            ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>();
            map.put("Dummy", "value");
        }
    }
}

When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)

Detection of NullPointerException

It is easier to detect NullPointerException. Check exception trace, it will tell you class name, method name and line number.Go to that line number and check what can be the reason for NullPointerException.


Fix NullPointerException

Let’s take above scenrios and fix NullPointerException.

1. Null check

check null before calling method or field.

package org.arpit.java2blog;
public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        Employee e1=null;
        if(e1!=null)
        {
            String name = e1.getName();
            System.out.println("Employee Name: "+ name);
        }
    }
}

When you run above program, you won’t get NullPointerExcpetion.

2. Do null check as well before putting key or value in Collection which do not allow null


Best practices for avoiding NullPointerException

1. String comparison

This is most frequent reason for Exception in thread main java.lang.NullPointerException, let’s understand with the help of example.

package org.arpit.java2blog;

public class StringComparisonMain {

    public static void main(String[] args) {
        Employee e1=new Employee();

        if(e1.getName().equalsIgnoreCase("John"))
        {
            System.out.println("Employee Name is John");
        }
    }
}

As we did not set name of Employee e1, we will get NullPointerException here.
When you run above program, you will get below output.

Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.StringComparisonMain.main(StringComparisonMain.java:8)

You can change logic as below.

package org.arpit.java2blog;

public class StringComparisonMain {

    public static void main(String[] args) {
        Employee e1=new Employee();

        if("John".equalsIgnoreCase(e1.getName()))
        {
            System.out.println("Employee Name is John");
        }
    }
}

This will avoid Exception in thread main java.lang.NullPointerException.
Please note that it may cause unexpected behavior due to null. If name cannot be null at all for Employee, then don’t use above method as it will ignore null names in this case.

2. Use Optional

Java 8 has introduced a new class called Optional.In general, we do not find any value in method, we return null from it and it becomes pain for caller to check for null to use it.
For example:

public static Employee findEmployee(List<Employee employeeList,String name)
{
    for(Employee e:employeeList)
    {
        if(e.getName().equalsIgnoreCase(name))
        {
            return e;
        }
    }
    return null;
}

As you can see, if we did not find employee in employeeList, we are returning null from findEmployee() method. The caller will get  employee object from findEmployee() method and may call getName() method which will in turn raise NullPointerException.You can use Optional to avoid such situations.

package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class JavaOptionalMain {

    public static void main(String[] args)
    {
        List<Employee> employeeList = createEmployeeList();
        Optional<Employee> employeeOpt = findEmployee(employeeList,"John");
        if(employeeOpt.isPresent())
        {
            Employee employee = employeeOpt.get();
            System.out.println("Employee name: "+employee.getName());
        }
        else
        {
            System.out.println("There is no employee with name John");
        }
    }

    public static Optional<Employee> findEmployee(List<Employee> employeeList,String name)
    {
        for(Employee e:employeeList)
        {
            if(e.getName().equalsIgnoreCase(name))
            {
                return Optional.of(e);
            }
        }
        return Optional.empty();
    }
    public static List<Employee> createEmployeeList()
    {
        List<Employee> employeeList=new ArrayList<>();

        Employee e1=new Employee("Adam",23);
        Employee e2=new Employee("Dave",34);
        Employee e3=new Employee("Carl",45);
        Employee e4=new Employee("Mohan",29);
        Employee e5=new Employee("Paresh",30);

        employeeList.add(e1);
        employeeList.add(e2);
        employeeList.add(e3);
        employeeList.add(e4);
        employeeList.add(e5);

        return employeeList;
    }
}
There is no employee with name John

It gives indication to caller than returned value can be null.

3. Use ternary opertor

You can use ternary operation to check for null.

package org.arpit.java2blog;
public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        Employee e1=null;

        String name = e1==null?e1.getName():"";
        System.out.println("Employee Name: "+ name);

    }
}

As you can see, we won’t get NullPointerException here.

4. Keep check on arguments of method

package org.arpit.java2blog;
public class InvokingMethodOnNullMain {

    public static void main(String[] args) {
        String str=null;
        int len=getLength(str);
        System.out.println("Length of String:"+ len);
    }

    public static int getLength(String str)
    {
        if(str!=null)
        {
            return str.length();
        }
        else
        {
            return 0;
        }
    }
}

5. Use StringUtils from Apache Common

You can use StringUtils class to take care of lots of String null and empty String check. Sometimes you need to check if String is null or empty, you can use isEmpty method from StringUtils to take care of it.

That’s all about Exception in thread "main" java.lang.NullPointerException in java.

]]>
https://java2blog.com/exception-thread-main-java-lang-nullpointerexception/feed/ 0
java.util.NoSuchElementException https://java2blog.com/java-util-nosuchelementexception/?utm_source=rss&utm_medium=rss&utm_campaign=java-util-nosuchelementexception https://java2blog.com/java-util-nosuchelementexception/#respond Sun, 22 Dec 2019 12:47:54 +0000 https://java2blog.com/?p=8202 java.util.NoSuchElementException is a RuntimeException or say an UncheckedException and therefore it does not need to be declared in a constructor’s or a method’s throw block.
java.util.NoSuchElementException is usually thrown when we try to access some element which is not present or reserved for the underlying data structure in the heap, and, thrown by the different classes, which have method to fetch the next element or next tokens, like Iterator :: next(), Enumeration :: nextElement() , StringTokenizer :: nextToken().
Example
When we are iterating over hashmap without implementing the condition to check if there is any element or not, this exception is raised or thrown by Java, now this is the reason we use hasNext() before calling next() on Iterator.

There can be multiple scenarios for java.util.NoSuchElementException. Let’s understand each with the help of examples.


Scenario 1: In case of Enumeration

In Enumeration, if we call the method nextElement() and there is no element present in enumeration then this exception is raised, refer the code below.
Syntax :

package org.arpit.java2blog;
import java.util.*;

class Main {
    public static void main(String args[]) {
        Hashtable hmap = new Hashtable();
        Enumeration enumer = hmap.elements();
        enumer.nextElement(); // java.util.NoSuchElementExcepiton 
                                // because the enumeration is empty
    }
}

Output:

Exception in thread “main” java.util.NoSuchElementException
at java.util.Collections$EmptyEnumeration.nextElement(Collections.j ava:4270)
at Main.main(Main.java:7)

Solution

By using a condition to check if it really have elements by calling method hasMoreElements().
Code:

package org.arpit.java2blog;
import java.util.*;

class Main {
    public static void main(String args[]) {
        Hashtable hmap = new Hashtable();
        Enumeration enumer = hmap.elements();
        if (enumer.hasMoreElements()) {
       //java.util.NoSuchElementExcepiton handled by checking enumer.nextElement();
        }
    }
}

Above program will run perfectly fine with no exceptions.


Scenario 2: In case of Iterator

In iterator, if we call the method next() and there is no element present in iterator then this exception is raised, refer the code below.

package org.arpit.java2blog;
import java.util.*;

class Main {

    public static void main(String args[]) {
        HashMap hMap = new HashMap();
        Iterator itr = hMap.keySet().iterator();
        itr.next();
//java.util.NoSuchElementException here because iterator is //empty
    }
}

Output:

Exception in thread “main” java.util.NoSuchElementException at
java.util.HashMap$HashIterator.nextNode(HashMap.java:1447) at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
at Main.main(Main.java:6)

Solution

By implementing a condition to check if there is any next element by calling method hasNext().
Code:

package org.arpit.java2blog;
import java.util.*;

class Main {
    public static void main(String args[]) {
        HashMap hMap = new HashMap();
        Iterator itr = hMap.keySet().iterator();
        if (itr.hasNext())
            itr.next(); // java.util.NoSuchElementExcepiton handled
    }
}

Now, this runs without throwing the given Exception.


Scenario 3: In case of StringTokenizer

In StringTokenizer, if we call the method nextElement() or nextToken() and there is no element or token present then this exception is raised, refer the code below.

package org.arpit.java2blog;
import java.util.StringTokenizer;

class Main {

    public static void main(String args[]) {
        StringTokenizer token = new StringTokenizer("", ":");
        System.out.println(token.nextToken());
    }
}

Output:

Exception in thread “main” java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken (StringTokenizer.java:349)
at Main.main (Main.java:5)

Solution

By using Stringtokenizer’s hasMoreTokens() or hashMoreElements() before proceding to call nextToken() or nextElement().
Code:

package org.arpit.java2blog;
import java.util.StringTokenizer;

class Main {
    public static void main(String args[]) {
        StringTokenizer token = new StringTokenizer("", ":");
        while (token.hasMoreTokens()) // Exception Handled
            System.out.println(token.nextToken());
    }

}

Above program will run perfectly fine with no exceptions.

]]>
https://java2blog.com/java-util-nosuchelementexception/feed/ 0
java.lang.StackOverflowError https://java2blog.com/java-lang-stackoverflowerror/?utm_source=rss&utm_medium=rss&utm_campaign=java-lang-stackoverflowerror https://java2blog.com/java-lang-stackoverflowerror/#respond Sat, 21 Dec 2019 17:08:28 +0000 https://java2blog.com/?p=8190 In this article, we will discuss about the java.lang.StackOverflowError by looking different code examples and also how can we avoid them.

More precisely, StackOverflowError is an error which Java doesn’t allow to catch, for instance ,stack running out of space, as it’s one of the most common runtime errors one can encounter, because it’s raising condition is implemented directly or indirectly in almost every module.

The main cause of the java.lang.StackOverflowError is that we haven’t provided the proper terminating condition to our recursive function or template, which means it will turn into an equivalent of an infinite loop.


How JVM invokes a method

To understand about java.lang.StackOverflowError, we need to understand how JVM invokes method internally. When a method is invoked, a new stack frame is created on the Thread Stack Size or on the call stack.
Now, that respective stack frame holds arguments of the invoked method, mainly the local variables and the return address of the that method. This creation of stack frames will be an iterative process, and will be stopped only when the end of method invocations is found inside nested methods.

In amid of this whole process, if JVM is running out of space for the new stack frames to be create, it will throw a java.lang.StackOverflowError.

( This is the reason, why we call it as JVM error also. )


Reasons for java.lang.StackOverflowError

There can be multiples reasons for java.lang.StackOverflowError

Poor or No Termination Condition

This is most common situation termed as unterminated or infinite recursion.

Let’s see an example where the error will be thrown as a result of the given condition:

In the following example, we are trying to print natural numbers, without providing the proper condition.

< pre class= "java" name= "code" >
public class java2blog
{
static int i=0 ; // declaring static variable it cannot be from a static context

public static int printNum (int x) // declaring static because 
//non-static method printNum(int) cannot be referenced from a static context
{
    i=i+1;
    System.out.println(i);
    return i+ printNum(i+1) ;
}

public static void main (String[] args) { 
    java2blog.printNum(i) ;
}

}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
..
..
Exception in thread "main" java.lang.StackOverflowError
at java2blog.printNum (java2blog.java:8)
at java2blog.printNum (java2blog.java:8)
at java2blog.printNum (java2blog.java:8)
at java2blog.printNum (java2blog.java:8)
at java2blog.printNum (java2blog.java:8)
at java2blog.printNum (java2blog.java:8)
at java2blog.printNum (java2blog.java:8)

Now, we can see due the absence of the termination condition the error was thrown. Also, note that these repeating line numbers will be infinite and they indicate that this function is being called recursively.

Solution

•   After you notice these repeating pattern, try to introduce a terminating condition or some base condition for the recursive calls.
•   Another approach could be, if you notice that you have implemented correctly still the same error is encountered, then we can avoid that by increasing the stack’s size in order to allow the larger number of recursive calls.

This can be easily done by changing the settings of our compiler.

< pre class= "java" name= "code" >
public class java2blog
{
static int i=0 ; // declaring static variable it cannot be from a static context

public static int printNum (int x) // declaring static because 
//non-static method printNum(int) cannot be referenced from a static context
{
    i=i+1;
    System.out.println(i);

    if(i==20) // Terminating condition introduced
        return i;
    return i+ printNum(i+1) ;
}

public static void main (String[] args) { 
    java2blog.printNum(i) ;
}

}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Due to the Cyclic Relationships Between Classes

Cyclic Relationship : When two different classes instantiate each other inside their constructors causes this relationship.

This ends up with a StackOverflowError because the constructor of ClassA is instantiating ClassB, and the constructor of ClassB is again instantiating ClassA, and it occurs repeatedly until the overflow.
< pre class= "java" name= "code" >
public class A
{
public B type2 ;
public A() {
type2 = new B () ; // object of class B is created and hence constructor of // B is invoked
}

public static void main ( String[] args) {
    A type1 = new A () ; // starting the cycle by invoking class A constructor

// at the time of object declaration (implicit)
}
}
class B
{
public A type1 ;
public B () {
type1= new A () ; // object of class A is created and hence constructor of // A is invoked
}
}

Output:

Exception in thread “main” java.lang.StackOverflowError
at B.(A.java:16)
at A.(A.java:5)
at B.(A.java:16)
at A.(A.java:5)
at B.(A.java:16)
at A.(A.java:5)
at B.(A.java:16)
at A.(A.java:5)
at B.(A.java:16)
at A.(A.java:5)
at B.(A.java:16)
at A.(A.java:5)
at B.(A.java:16)

Repetitive calls here shows the infinite recursion

Solution

Now, the error here is mainly due to the constructors calling each other repetitively, so we have to make sure that while implementing different classes, the above condition should not arise.
Since there is no significance of this cyclic constructors invocations so we can avoid them, as they are already invoked implicitly at the time of the creation of the objects of their respective classes.

That’s all about java.lang.StackOverflowError in java.

]]>
https://java2blog.com/java-lang-stackoverflowerror/feed/ 0
java.lang.NumberFormatException https://java2blog.com/java-lang-numberformatexception/?utm_source=rss&utm_medium=rss&utm_campaign=java-lang-numberformatexception https://java2blog.com/java-lang-numberformatexception/#respond Sat, 05 Oct 2019 09:59:09 +0000 https://java2blog.com/?p=7463 In this post, we will see about Java.lang.NumberFormatException.

java.lang.NumberFormatException occurs where you try to convert any non-numeric String to Number such as Integer, Double, Float or Long.

This exception generally occurs when you get input from user in the form of String. This is not Java developer‘s fault and mostly data error. In this scenario, data should be corrected and you can log the error to log file for analysis later. If you do not handle the application then the application might crash.

Let’s understand it with the help of an example.

package org.arpit.java2blog;

import java.util.Scanner;

public class StringToIntegerConversion {

    public static void main(String[] args) {
        Scanner scanner = null ;
        try {
            System.out.println("Please enter a number:"); 
            scanner = new Scanner(System.in); 
            String inputStr = scanner.nextLine();

            int i = Integer.parseInt(inputStr);

            //If NumberFormatException occurs, this will become unreachable code
            System.out.println("Converted int value = " + i);
        }
        catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        finally
        {
            scanner.close();
        }
    }
}

When you run above program, you will get below output:

Iteration 1: Put correct Integer value

Please enter a number:
10
Converted int value = 10

Iteration 2: Put NA as user input

Please enter a number:
NA
java.lang.NumberFormatException: For input string: “NA”
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 org.arpit.java2blog.StringToIntegerConversion.main(StringToIntegerConversion.java:14)

As "NA" can not be converted to Integer, it will throw above exception.

Iteration 3: Put “” as user input

Please enter a number:
java.lang.NumberFormatException: For input string: “”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at org.arpit.java2blog.StringToIntegerConversion.main(StringToIntegerConversion.java:14)

As "" can not be converted to Integer, it will throw above exception.

Iteration 4: Put “1.0” as user input

Please enter a number:
1.0
java.lang.NumberFormatException: For input string: “1.0”
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 org.arpit.java2blog.StringToIntegerConversion.main(StringToIntegerConversion.java:14)

It is also necessay that given input string should be able to convert to target data type as "1.0" can not be converted to Integer.


How to resolve java.lang.NumberFormatException

If you are getting java.lang.NumberFormatException, you can easily find information in exception itself.

For example:

java.lang.NumberFormatException: For input string: “NA”

As NA is alphanumeric and can not be converted to Integer.

Only way to avoid this exception is correct the input data and you should put proper exception handling whenever you are doing String to Number conversion.

]]>
https://java2blog.com/java-lang-numberformatexception/feed/ 0
FileNotFoundException in Java https://java2blog.com/filenotfoundexception-java/?utm_source=rss&utm_medium=rss&utm_campaign=filenotfoundexception-java https://java2blog.com/filenotfoundexception-java/#respond Thu, 09 May 2019 17:47:24 +0000 https://java2blog.com/?p=7438 In this post, we will see about FileNotFoundException in java.

FileNotFoundException is thrown by constructors of FileInputStream, FileOutputStream, RandomAccessFile when file is not found on specified path. Exception can also be raised when file is inaccessible for some reason.For example: When you do not have proper permissions to read the files.

FileNotFoundException is checked exception so you need to handle by java code. You should take proper action to print appropriate exception to the user if FileNotFoundException is thrown.

Let’s understand with the help of example.

package org.arpit.java2blog;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* FileNotFoundException example
* @author Arpit
*
*/
public class FileReadExample {
    public static void main(String[] args) {
        File file = new File("C:/Java2blog.txt");
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(file);
            while (fis.read()!=-1){
                System.out.println(fis.read());
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            try{
                fis.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}
When you run above program, you will get below output:

java.io.FileNotFoundException: C:/Java2blog.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.(FileInputStream.java:139)
at org.arpit.java2blog.FileReadExample.main(FileReadExample.java:17)
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.FileReadExample.main(FileReadExample.java:27)

As you can see if file is not present in the path, we are getting FileNotFoundException


How to resolve FileNotFoundException

  • Check if passed file is present in specified file
  • Check if passed file is actually directory
  • The passed file can not be open due to permission issues. You might be trying to write to file where as you only have read permission.
  • Check if passed file name does not contain any invisible characters such as \r\n symbols.

That’s all about FileNotFoundException in java.

]]>
https://java2blog.com/filenotfoundexception-java/feed/ 0