Java for C# Programmers 4: Exceptions & Arrays


Java has exceptions with try/catch/finally. They work roughly the same way as in C#.

  • Gotcha: In C#, the stack trace is put into the exception when the exception is thrown. In Java, the stack trace is calculated, when the exception is created. Re-read the previous sentence, please.
  • Rethrowing an exception in Java works like this:
    catch (Exception e) { throw e; }
    This works in Java only because throwing an exception does not recalculate its stack.
  • The ex.getMessage() may be null, even with standard system exceptions. This is never the case in C#. At least I’ve never seen it there.
  • On the other hand, you can call System.out.println(ex.getMessage()); without problems in Java. It writes null to the screen. In C#, this will throw, if ex.getMessage() is null.
  • Gotcha: In Java return is allowed in a finally block, which is not in C#. This may lead to unexpected behaviour.
  • You can catch multiple types of exceptions in one clause.
    catch ( IOException | SQLException ex ) { ... }

Checked Exceptions

In Java, there are two types of exceptions. Checked and unchecked exceptions. Unchecked exceptions are those which derive from RuntimeException, checked exceptions extend Exception. In C#, there are only unchecked exceptions.

Checked exceptions are an interesting feature.

If a method X can throw one or several checked exceptions, it must announce this in its declaration with the throws keyword like this:
void ReadMyFile(String filename) throws IOException

What follows: if a method M calls a method X which may throw a checked exception Ex,

  • M itself must catch Ex or
  • M itself declares that it may throw Ex via throws Ex

This is enforced by the compiler.
At first glance, it seems that checked exceptions make things easier for library developers and library users… But at second glance, it seems checked exceptions are deprecated in the Java community. Probably the main point of this interesting post about checked exceptions is:

When you choose to use checked exception for errors that you think are recoverable, you try to decide for the client of your API, whereas only he may know what’s recoverable and what isn’t in his own context.

Hejlsberg, the main developer of C#, doesn’t like checked exceptions too much also. In an interview about checked exceptions he stated:

The exception handling should be centralized, and you should just protect yourself as the exceptions propagate out to the handler.


There are constant length arrays in Java, which are very similar to those in C#. Access is by index starting at zero.

Gotcha: In Java, the array is not connected in any way to the Iterable interface or the collection types. You cannot pass an array where an Iterable is required.

Exception: you can use an array in a for loop.

int[] h4 = {4, 5, 11, 46};
for(int i: h4)
    System.out.printf(" %d", i);  // 4 5 11 46

Creating an Array

Some examples of how to create an array in Java are:

Abc[] a = new Abc[6]; 
  // All members of a are initialized to null, as 
  // Abc is a reference type.

int b[] = new int[4]; 
for(int i = 0; i < a.length; ++i)
    System.out.print(a[i] + " ");   // 0 0 0 0 

b[6] = 67;   // ArrayIndexOutOfBoundsException: 6   

int[] c = new int[] {4, 5, 11};
int[] d = {4, 5, 11, 46};

String[] e = {"a", "b"};

int[] g = new int[5];

Copying an Array or a Part

There are at least three different system methods to copy an array. I am not really sure what are the differences. Probably there are none or none worth to mention.

int[] d = {4, 5, 11, 46};
int[] g = new int[5];
int[] f = d.clone();    // copies d completely

// Copies 3 elements starting at f[0] to g, 
// starting at g[1].
System.arraycopy(f, 0, g, 1, 3);
System.out.println(Arrays.toString(g)); // [0, 4, 5, 11, 0]

int[] h = Arrays.copyOf(d, 3);
System.out.println(h);                  // [I@1b778d0c      
System.out.println(Arrays.toString(h)); // [4, 5, 6]

Class Arrays

The static system class Arrays contains some functions - even some parallel ones - that are helpful when dealing with arrays. The functions are overloaded for all the primitive types and for Object.

Function Purpose
asList creates a List from an array
binarySearch searches an item
copyOf copies, truncating or padding
copyOfRange copies a part
deepEquals checks if 2 arrays are deeply equal
deepToString returns a deep string representation
fill fills an array or a part of an array
parallelPrefix cumulates in parallel all elements
parallelSetAll fills in parallel with generated values
parallelSort sorts an array using a parallel algorithm
setAll fills with generated values
sort sorts completely or sort a range
stream creates a Stream from array
spliterator creates a Spliterator from array

Multi-Dimensional Arrays

An array of arrays (jagged array) is possible and the only type in Java. Real multi-dimensional arrays like in C, C++ and C# do not exist in Java.

int[][] h21 = new int[2][4]; 
int[][][] h3 = new int[2][5][4];

System.out.println(h3.length);          // 2 
System.out.println(h3[0].length);       // 5 
System.out.println(h3[0][0].length);    // 4 

You should always remember that jagged arrays are just arrays of arrays (of arrays, ...) and the length of the second (third, ...) level arrays may be different for every entry.

int[][] h22 = { {11, 12, 13, 14}, {5} };

System.out.println(h22[0].length);      // 4 
System.out.println(h22[1].length);      // 1 

System.out.println(h22[0][3]); // 14 
System.out.println(h22[1][3]); // throws ArrayIndexOutOfBoundsException

It seems the best way to find out the number of dimensions of a multi-dimensional array is to go via the class name.

int[][][][] a = {{{{1},{71}}}};

String className = a.getClass().getName();
System.out.println(className);              // [[[[I
int numberOfDimensions = className.lastIndexOf('[') + 1;
System.out.println(numberOfDimensions);     // 4

1 thought on “Java for C# Programmers 4: Exceptions & Arrays

Comments are closed.