Ошибка java неверный аргумент

Наконец, я нашел причину.
Сначала я замечаю, что НЕ всегда это исключение приходит
в той же точке.

Иногда был   java.io.IOException: неверный аргумент       в java.io.FileOutputStream.close0 (собственный метод)       в java.io.FileOutputStream.close(FileOutputStream.java:279)                                   ^^^^^

и иногда был

java.io.IOException: Invalid argument
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)

Поэтому проблема НЕ является проблемой Java. Даже проблема NFS.
Проблема базовый тип файловой системы, который является DRBD
файловой системы.

Тестирование в оболочке для записи по узлам работает, если вы пишете небольшую
файл. То есть:

на установленном nfs node

cd /tmp
date > /shared/path-to-some-not-mounted-dir/today

will work

но

cat myBigFile > /shared/path-to-some-not-mounted-dir/today

выдаст следующую ошибку

cat: write error: Invalid argument

Поэтому решение заключается в использовании другого типа файловой системы, например gfs.

I am kind of new to java so pardon this rather simple question, I guess. This method will count how many digits are there on a POSITIVE integer only. So it needs to throw an error to the caller. How do I do so when the input is negative, I throw an error and exit the method without returning anything?

public static int countDigits(int n)
    {
        if (n<0)
        {
            System.out.println("Error! Input should be positive");
            return -1;
        }
        int result = 0; 
        while ((n/10) != 0)
        {
            result++;
            n/=10;
        }
        return result + 1;
    }

Tobias's user avatar

Tobias

7,6831 gold badge27 silver badges44 bronze badges

asked Sep 10, 2015 at 16:05

Gavin's user avatar

1

You’re not throwing an error here; you’re displaying an error message and returning a sentinel value of -1.

If you want to throw an error, you have to use the throw keyword, followed by an appropriate Exception.

public static int countDigits(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("Input should be positive");
    }
    int result = 0;
    while ((n / 10) != 0) {
        result++;
        n /= 10;
    }
    return result + 1;
}

The Java Trails on throwing exceptions will provide you with invaluable insights into what different kinds of exceptions there are. Above, IllegalArgumentException is considered a runtime exception, so something that is calling this method won’t be forced to catch its exception.

answered Sep 10, 2015 at 16:08

Makoto's user avatar

MakotoMakoto

103k27 gold badges191 silver badges227 bronze badges

You need to throw an exception.

if (n < 0) {

    throw new Exception("n must be a positive integer");
}

You can make life easier for callers of your method by using a more specific exception type. In this case, IllegalArgumentException would be appropriate.

if (n < 0) {

    throw new IllegalArgumentException("n must be a positive integer");
}

Different types of error can be handled separately in a try-catch.

I would take a look at Guava’s preconditions to do this in a cleaner fashion.

answered Sep 10, 2015 at 16:08

sdgfsdh's user avatar

sdgfsdhsdgfsdh

32.5k25 gold badges127 silver badges230 bronze badges

1

It depends. If the caller doesn’t handle an eventual failure, then I’d throw an exception. But it is much simpler to return a value like -1 and then check the result after the call. Exceptions are slow.

answered Sep 10, 2015 at 16:11

Danis's user avatar

5

Мой новый ноутбук (Alienware M17x) выбрасывает java.net.SocketException: Invalid argument: connect когда я запускаю следующий основной код:

Server.java:

public static void main (String[] args) throws Exception {

    ServerSocket serverSocket = new ServerSocket (8888);
    Socket socket = serverSocket.accept();
}

Client.java:

public static void main (String[] args) throws Exception {
    Socket socket = new Socket ("localhost", 8888);
}

Каждый раз, когда я запускаю Client.java (после запуска Server.java), я получаю это исключение сокета. Вот полный след исключения:

Exception in thread "main" java.net.SocketException: Invalid argument: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at Client.main(Client.java:5)

Я попробовал несколько вещей, но не повезло, исключение всегда выбрасывается. Вот что я пришел к выводу:

  • Изменение номеров портов ничего не меняет.
  • Это не проблема с сетью. Я получил исключение в школе и дома.
  • Я переустановил JVM и JDK, но не повезло.
  • Это происходит только на одной машине. Я запустил тот же код на своем рабочем столе, и я не получил никаких исключений. Я использую Windows 7 на обоих.
  • Он не заблокирован брандмауэром. Я выключил свои брандмауэры, и у меня все еще есть эта проблема.

Что я должен сделать или проверить, чтобы решить эту проблему?

РЕДАКТИРОВАТЬ: маршрут печати результатов:

===========================================================================
Interface List
 15...e4 d5 3d 08 cb 83 ......Killer Wireless-N 1103 Network Adapter
 13...d0 df 9a b5 73 dc ......Bluetooth Device (Personal Area Network)
 11...d4 be d9 00 10 65 ......Atheros AR8151 PCI-E Gigabit Ethernet Controller (NDIS 6.20)
  1...........................Software Loopback Interface 1
 17...00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
 16...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
 18...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
 19...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.0.1    192.168.0.191     25
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    306
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    306
      192.168.0.0    255.255.255.0         On-link     192.168.0.191    281
    192.168.0.191  255.255.255.255         On-link     192.168.0.191    281
    192.168.0.255  255.255.255.255         On-link     192.168.0.191    281
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    306
        224.0.0.0        240.0.0.0         On-link     192.168.0.191    281
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    306
  255.255.255.255  255.255.255.255         On-link     192.168.0.191    281
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
 17     58 ::/0                     On-link
  1    306 ::1/128                  On-link
 17     58 2001::/32                On-link
 17    306 2001:0:4137:9e76:28f3:2721:524f:e2ef/128
                                    On-link
 15    281 fe80::/64                On-link
 17    306 fe80::/64                On-link
 17    306 fe80::28f3:2721:524f:e2ef/128
                                    On-link
 15    281 fe80::68c1:bc79:fefa:88a2/128
                                    On-link
  1    306 ff00::/8                 On-link
 17    306 ff00::/8                 On-link
 15    281 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

РЕДАКТИРОВАТЬ: Как @PhilippeLM и @beny23 заставили меня понять, что установка системной переменной java java.net.preferIPv4Stack в значение true решает мою проблему. Однако я хочу постоянное исправление. Я не хочу указывать системную переменную каждый раз, когда я запускаю Java-приложение.

Вот что я попробовал без удачи еще раз:

  • Чтобы настроить параметры моего компьютера на использование IPv4, выполните следующие действия.
  • Добавление строки java.net.preferIPv4Stack=true к net.properties файл в %JAVA_HOME%jrelib,

Есть ли что-нибудь еще, что я могу попробовать?

2011-11-21 18:34

8
ответов

Решение

У меня Alienware m17x R3, и я обнаружил, что у меня точно такая же ошибка с Java, хотя я столкнулся с ней с Minecraft. Установка более старой Java6u33 устранила проблему, но я обнаружил, что новые обновления Java7 все еще не работали даже после нескольких месяцев ожидания. В итоге я зашел на сайт Dell и скачал самые последние сетевые драйверы для моего ноутбука Alienware (поскольку Alienware теперь принадлежит Dell), и это сразу же решило проблему.

2012-09-24 02:59

Работает ли это, если вы скажете Java использовать стек IPv4?

Используйте следующую опцию командной строки при запуске сервера и клиента.

-Djava.net.preferIPv4Stack=true

Смотрите также здесь

2011-11-28 20:36

Кажется, ваша машина имеет конфигурацию IPv6 и по умолчанию предпочтительнее в Java, поэтому попробуйте запустить ваш сервер и клиент с параметром -Djava.net.preferIPv4Stack=true в качестве аргументов JVM:

  java -Djava.net.preferIPv4Stack=true Client.main

Также убедитесь, что вы не запретили доступ к сети приложения, когда брандмауэр Windows запросил разрешение. Если вы это сделали, вы можете изменить настройки на панели управления.

2011-12-01 19:52

Существует ошибка Windows, которая затрагивает не только Java-приложения и выдает именно эту ошибку в определенных созвездиях, где JRE находится на сетевом ресурсе: https://bugs.openjdk.java.net/browse/JDK-8068568

Решением является либо использование установки JRE на локальном диске, либо предоставление разрешения «Список папок» на все папки-предки исполняемого файла JRE.

В https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/3076a9cd-57a0-418d-8de1-07adc3b486bb предлагается добавить значение DWORD HKEY_LOCAL_MACHINESYSTEMCurrentControlSetservicesFlttMgrUseTildeSDedeSDede_SD контент «1», который у меня не было возможности попробовать. Я также помню, что читал пост на форуме поддержки Microsoft, в котором говорилось, что этого не происходит в сетевых ресурсах, имя которых длиннее 8 символов, но я больше не могу найти этот пост.

2018-03-08 09:46

Я нашел способ сделать это постоянным изменением отсюда.

Что вам нужно сделать, это добавить системную переменную с именем JAVA_TOOL_OPTIONS и установить для нее все, что вы хотите передать в java в качестве аргумента командной строки при каждом запуске, в вашем и моем случае.

-Djava.net.preferIPv4Stack=true

2012-03-29 01:05

Также проверьте, использует ли ваша IDE JRE, которую вы ожидаете.
У меня была такая же проблема:

java.sql.SQLException: JZ006: Caught IOException: java.net.SocketException: Invalid argument: create

Когда я проверял свою конфигурацию запуска, мой JRE по умолчанию указывал на «Среду выполнения проекта» JavaSE1.7 «, чего я не ожидал.

Я изменил его на опцию Alternate JRE и установил JAVA 8 в качестве установленного jre. который решил мою проблему.

2017-12-07 12:57

Пожалуйста, проверьте, установлен ли JDK в сетевой папке. если да, пожалуйста, измените расположение jdk на диске локального диска и подтвердите, что нет никаких ограничений на разрешение

2018-08-24 02:44

Можете ли вы запустить другие приложения, которые подключаются к сети или локальному хосту? У меня была похожая проблема некоторое время назад (только на Win7), и я исправил ее, только перейдя к Network connection-> Repain, Проблема возникла из-за того, что моя таблица маршрутизации была повреждена, localhost Маршрут исчез из него, и любое приложение пытается подключиться к localhost сбой с той же ошибкой, что и у вас.

Ты можешь бежать route -print в командной строке и выложить вывод?

РЕДАКТИРОВАТЬ: Похоже, ваш стек IP поврежден, вы можете попробовать это исправить от MS

2011-11-21 18:48

A quick guide to how to fix IllegalArgumentException in java and java 8?

1. Overview

In this tutorial, We’ll learn when IllegalArgumentException is thrown and how to solve IllegalArgumentException in java 8 programming.

This is a very common exception thrown by the java runtime for any invalid inputs. IllegalArgumentException is part of java.lang package and this is an unchecked exception.

IllegalArgumentException is extensively used in java api development and used by many classes even in java 8 stream api.

First, we will see when we get IllegalArgumentException in java with examples and next will understand how to troubleshoot and solve this problem?

Java - How to Solve IllegalArgumentException?

2. Java.lang.IllegalArgumentException Simulation

In the below example, first crated the ArrayList instance and added few string values to it. 

package com.javaprogramto.exception.IllegalArgumentException;

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

public class IllegalArgumentExceptionExample {

	public static void main(String[] args) {
		
		// Example 1
		List<String> list = new ArrayList<>(-10);
		list.add("a");
		list.add("b");
		list.add("c");
	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Illegal Capacity: -10
	at java.base/java.util.ArrayList.<init>(ArrayList.java:160)
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:11)

From the above output, we could see the illegal argument exception while creating the ArrayList instance.

Few other java api including java 8 stream api and custom exceptions.

3. Java IllegalArgumentException Simulation using Java 8 stream api

Java 8 stream api has the skip() method which is used to skip the first n objects of the stream.

public class IllegalArgumentExceptionExample2 {

	public static void main(String[] args) {
		
		// Example 2
		List<String> stringsList = new ArrayList<>();
		stringsList.add("a");
		stringsList.add("b");
		stringsList.add("c");
		
		stringsList.stream().skip(-100);
	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: -100
	at java.base/java.util.stream.ReferencePipeline.skip(ReferencePipeline.java:476)
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample2.main(IllegalArgumentExceptionExample2.java:16)

4. Java IllegalArgumentException — throwing from custom condition

In the below code, we are checking the employee age that should be in between 18 and 65. The remaining age groups are not allowed for any job.

Now, if we get the employee object below 18 or above 65 then we need to reject the employee request.

So, we will use the illegal argument exception to throw the error.

import com.javaprogramto.java8.compare.Employee;

public class IllegalArgumentExceptionExample3 {

	public static void main(String[] args) {

		// Example 3
		Employee employeeRequest = new Employee(222, "Ram", 17);

		if (employeeRequest.getAge() < 18 || employeeRequest.getAge() > 65) {
			throw new IllegalArgumentException("Invalid age for the emp req");
		}

	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid age for the emp req
	at com.javaprogramto.exception.IllegalArgumentException.IllegalArgumentExceptionExample3.main(IllegalArgumentExceptionExample3.java:13)

5. Solving IllegalArgumentException in Java

After seeing the few examples on IllegalArgumentException, you might have got an understanding on when it is thrown by the API or custom conditions based.

IllegalArgumentException is thrown only if any one or more method arguments are not in its range. That means values are not passed correctly.

If IllegalArgumentException is thrown by the java api methods then to solve, you need to look at the error stack trace for the exact location of the file and line number.

To solve IllegalArgumentException, we need to correct method values passed to it. But, in some cases it is completely valid to throw this exception by the programmers for the specific conditions. In this case, we use it as validations with the proper error message.

Below code is the solution for all java api methods. But for the condition based, you can wrap it inside try/catch block. But this is not recommended.

package com.javaprogramto.exception.IllegalArgumentException;

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

import com.javaprogramto.java8.compare.Employee;

public class IllegalArgumentExceptionExample4 {

	public static void main(String[] args) {

		// Example 1
		List<String> list = new ArrayList<>(10);
		list.add("a");
		list.add("b");
		list.add("c");

		// Example 2
		List<String> stringsList = new ArrayList<>();
		stringsList.add("a");
		stringsList.add("b");
		stringsList.add("c");

		stringsList.stream().skip(2);

		// Example 3
		Employee employeeRequest = new Employee(222, "Ram", 20);

		if (employeeRequest.getAge() < 18 || employeeRequest.getAge() > 65) {
			throw new IllegalArgumentException("Invalid age for the emp req");
		}
		
		System.out.println("No errors");

	}
}

Output:

6. Conclusion

In this article, We’ve seen how to solve IllegalArgumentException in java.

GitHub

IllegalArgumentException

The IllegalArgumentException is an unchecked exception in Java that is thrown to indicate an illegal or unsuitable argument passed to a method. It is one of the most common exceptions that occur in Java.

Since IllegalArgumentException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor.

What Causes IllegalArgumentException

An IllegalArgumentExceptioncode> occurs when an argument passed to a method doesn’t fit within the logic of the usage of the argument. Some of the most common scenarios for this are:

  1. When the arguments passed to a method are out of range. For example, if a method declares an integer age as a parameter, which is expected to be a positive integer. If a negative integer value is passed, an IllegalArgumentException will be thrown.
  2. When the format of an argument is invalid. For example, if a method declares a string email as a parameter, which is expected in an email address format.
  3. If a null object is passed to a method when it expects a non-empty object as an argument.

IllegalArgumentException Example

Here is an example of a IllegalArgumentException thrown when the argument passed to a method is out of range:

public class Person {
    int age;

    public void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age must be greater than zero");
        } else {
            this.age = age;
        }
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setAge(-1);
    }
}

In this example, the main() method calls the setAge() method with the agecode> argument set to -1. Since setAge()code> expects age to be a positive number, it throws an IllegalArgumentExceptioncode>:

Exception in thread "main" java.lang.IllegalArgumentException: Age must be greater than zero
    at Person.setAge(Person.java:6)
    at Person.main(Person.java:14)

How to Resolve IllegalArgumentException

The following steps should be followed to resolve an IllegalArgumentException in Java:

  1. Inspect the exception stack trace and identify the method that passes the illegal argument.
  2. Update the code to make sure that the passed argument is valid within the method that uses it.
  3. To catch the IllegalArgumentException, try-catch blocks can be used. Certain situations can be handled using a try-catch block such as asking for user input again instead of stopping execution when an illegal argument is encountered.

Track, Analyze and Manage Java Errors With Rollbar

![Rollbar in action](https://rollbar.com/wp-content/uploads/2022/04/section-1-real-time-errors@2x-1-300×202.png)

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.

In this tutorial, we will discuss how to solve the java.lang.illegalargumentexception – IllegalArgumentException in Java.

This exception is thrown in order to indicate that a method has been passed an illegal or inappropriate argument. For example, if a method requires a non-empty string as a parameter and the input string equals null, the IllegalArgumentException is thrown to indicate that the input parameter cannot be null.

You can also check this tutorial in the following video:

java.lang.IllegalArgumentException – Video

This exception extends the RuntimeException class and thus belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause. Finally, the IllegalArgumentException exists since the first version of Java (1.0).

java.lang.IllegalArgumentException

The IllegalArgumentException is a good way of handling possible errors in your application’s code. This exception indicates that a method is called with incorrect input arguments. Then, the only thing you must do is correct the values of the input parameters. In order to achieve that, follow the call stack found in the stack trace and check which method produced the invalid argument.

The following example indicates a sample usage of the java.lang.IllegalArgumentException – IllegalArgumentException.

IllegalArgumentExceptionExample.java

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

import java.io.File;

public class IllegalArgumentExceptionExample {

    /**

     *

     * @param parent, The path of the parent node.

     * @param filename, The filename of the current node.

     * @return The relative path to the current node, starting from the parent node.

     */

    public static String createRelativePath(String parent, String filename) {

        if(parent == null)

            throw new IllegalArgumentException("The parent path cannot be null!");

        if(filename == null)

            throw new IllegalArgumentException("The filename cannot be null!");

        return parent + File.separator + filename;

    }

    public static void main(String[] args) {

        System.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));

        System.out.println();

        System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));

    }

}

A sample execution is shown below:

dir1/file1
Exception in thread "main" 

java.lang.IllegalArgumentException: The parent path cannot be null!
	at main.java.IllegalArgumentExceptionExample.createRelativePath(IllegalArgumentExceptionExample.java:15)
	at main.java.IllegalArgumentExceptionExample.main(IllegalArgumentExceptionExample.java:29)

2. How to deal with the java.lang.IllegalArgumentException

  • When the IllegalArgumentException is thrown, you must check the call stack in Java’s stack trace and locate the method that produced the wrong argument.
  • The IllegalArgumentException is very useful and can be used to avoid situations where your application’s code would have to deal with unchecked input data.

3. Download the Eclipse Project

 This was a tutorial about IllegalArgumentException in Java.

Last updated on Oct. 12th, 2021

Photo of Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

(*env).CallObjectMethod(theUnsafe, defineClassID, name, data, n0, dataSize, classLoader, NULL);

This is not correct. Did you make it up? Don’t do that. Read the JNI Specification. It should be:

env->CallObjectMethod(theUnsafe, defineClassID, name, data, n0, dataSize, classLoader, NULL);

For completeness, in C it should be:

(*env)->CallObjectMethod(env, theUnsafe, defineClassID, name, data, n0, dataSize, classLoader, NULL);

Я даю команду, подобную этой bash-3.00$/app/jdk1.6.0_11/bin/java -version , она дает ошибку, например bash-3.00: /app/jdk1.6.0_11/bin/java: неверный аргумент

person
Vikas
  
schedule
24.02.2012
  
source
источник


Ответы (2)

«Недопустимый аргумент» — это ошибка, которую вы получаете в Solaris при попытке запустить двоичный файл SPARC на платформе x86. Убедитесь, что среда выполнения Java, которую вы установили в /app, подходит для вашего оборудования. Вы можете использовать команду file, чтобы проверить, например:

% file /net/pkg/export/pkg.sparc.sunos5/gnu/bin/ls
/net/pkg/export/pkg.sparc.sunos5/gnu/bin/ls:    ELF 32-bit MSB executable SPARC Version 1, dynamically linked, not stripped

% file /net/pkg/export/pkg.i386.sunos5/gnu/bin/tar
/net/pkg/export/pkg.i386.sunos5/gnu/bin/tar:    ELF 32-bit LSB executable 80386 Version 1, dynamically linked, not stripped

person
alanc
  
schedule
24.02.2012

Пытаться

bash-3.00$ source /app/jdk1.6.0_11/bin/java -version

or

bash-3.00$ . /app/jdk1.6.0_11/bin/java -version

(руководство по Bash)

Я предлагаю вам добавить путь Java JDK в переменную среды Bash PATH, поэтому вам не нужно писать весь путь.

person
m0skit0
  
schedule
24.02.2012

I am kind of new to java so pardon this rather simple question, I guess. This method will count how many digits are there on a POSITIVE integer only. So it needs to throw an error to the caller. How do I do so when the input is negative, I throw an error and exit the method without returning anything?

public static int countDigits(int n)
    {
        if (n<0)
        {
            System.out.println("Error! Input should be positive");
            return -1;
        }
        int result = 0; 
        while ((n/10) != 0)
        {
            result++;
            n/=10;
        }
        return result + 1;
    }

Tobias's user avatar

Tobias

7,7031 gold badge27 silver badges44 bronze badges

asked Sep 10, 2015 at 16:05

Gavin's user avatar

1

You’re not throwing an error here; you’re displaying an error message and returning a sentinel value of -1.

If you want to throw an error, you have to use the throw keyword, followed by an appropriate Exception.

public static int countDigits(int n) {
    if (n < 0) {
        throw new IllegalArgumentException("Input should be positive");
    }
    int result = 0;
    while ((n / 10) != 0) {
        result++;
        n /= 10;
    }
    return result + 1;
}

The Java Trails on throwing exceptions will provide you with invaluable insights into what different kinds of exceptions there are. Above, IllegalArgumentException is considered a runtime exception, so something that is calling this method won’t be forced to catch its exception.

answered Sep 10, 2015 at 16:08

Makoto's user avatar

MakotoMakoto

104k27 gold badges189 silver badges228 bronze badges

You need to throw an exception.

if (n < 0) {

    throw new Exception("n must be a positive integer");
}

You can make life easier for callers of your method by using a more specific exception type. In this case, IllegalArgumentException would be appropriate.

if (n < 0) {

    throw new IllegalArgumentException("n must be a positive integer");
}

Different types of error can be handled separately in a try-catch.

I would take a look at Guava’s preconditions to do this in a cleaner fashion.

answered Sep 10, 2015 at 16:08

sdgfsdh's user avatar

sdgfsdhsdgfsdh

33.1k26 gold badges129 silver badges236 bronze badges

1

It depends. If the caller doesn’t handle an eventual failure, then I’d throw an exception. But it is much simpler to return a value like -1 and then check the result after the call. Exceptions are slow.

answered Sep 10, 2015 at 16:11

Danis's user avatar

5

Наконец, я нашел причину.
Сначала я замечаю, что НЕ всегда это исключение приходит
в той же точке.

Иногда был   java.io.IOException: неверный аргумент       в java.io.FileOutputStream.close0 (собственный метод)       в java.io.FileOutputStream.close(FileOutputStream.java:279)                                   ^^^^^

и иногда был

java.io.IOException: Invalid argument
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:260)

Поэтому проблема НЕ является проблемой Java. Даже проблема NFS.
Проблема базовый тип файловой системы, который является DRBD
файловой системы.

Тестирование в оболочке для записи по узлам работает, если вы пишете небольшую
файл. То есть:

на установленном nfs node

cd /tmp
date > /shared/path-to-some-not-mounted-dir/today

will work

но

cat myBigFile > /shared/path-to-some-not-mounted-dir/today

выдаст следующую ошибку

cat: write error: Invalid argument

Поэтому решение заключается в использовании другого типа файловой системы, например gfs.

  • Ошибка java на кнопочном телефоне
  • Ошибка java virtual machine launcher error a jni error has occurred please
  • Ошибка java util concurrentmodificationexception
  • Ошибка java unexpected token
  • Ошибка java unable to launch the application