GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||
GeezerVison is showing www.tutorialspoint.com — Java - NegativeArraySizeException
Selected Reading
Java - NegativeArraySizeExceptionThe NegativeArraySizeException in Java occurs when an attempt is made to create an array with a negative size. This is a runtime exception. Following is the reason when JVM throws a NegativeArraySizeException in Java:
Methods of NegativeArraySizeExceptionThere are some methods of NegativeArraySizeException class:
Example of NegativeArraySizeExceptionIn this example, we are creating an array with a negative size, so JVM will throw a NegativeArraySizeException. public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
int[] arr = new int[-5];
}
}
OutputFollowing is the output of the above code: Exception in thread "main" java.lang.NegativeArraySizeException at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:3) As you can see in the output, JVM throws a NegativeArraySizeException because we are creating an array with a negative size. Handling NegativeArraySizeExceptionIn this example, we are creating an array with a negative size, so JVM will throw a NegativeArraySizeException. We are handling this exception using a try-catch block. public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
try {
int[] arr = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("Array size should be non-negative");
}
}
}
OutputFollowing is the output of the above code: Array size should be non-negative How to avoid NegativeArraySizeException?To avoid a NegativeArraySizeException, you should always create an array with a non-negative size. java_lang_exceptions.htm Advertisements
| ||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |