Suggestions for Using Exceptions inside Java

the particular

hook (NullPointerException e)

System.out.println(“refVar is null!”);

This is pure overkill. You can instead use the much simpler if statement to handle these types of simple errors.

if (refVar!=null)

System.out.println(refVar.toString();

in addition

System. out. println(“refVar will be null”);

If your program code can perform a basic logic analyze, as shown here, to manage a good error, do so, quite in comparison with using an exemption target to handle the fault.

Whenever you nor catch or toss exclusions
When anyone call almost any method of which throws the checked exclusion, you must both toss the exception to this rule or find it. If 程序代写 choose which you can’t handle typically the exemption in the procedure where that occurs, create some sort of place statement for you to send this exception right up to the calling method, which must then both handle it with an exception to this rule handler, or chuck it up to its calling process.

The right away set of examples indicate how you must either hook or throw a good looked at exception, in buy to avoid compiler problems.

The first example indicates passcode that throws the IOException. The statement inside the process getFileLength may well throw an IO exception to this rule when it cell phone calls the constructor of the RandomAccessFile class. In addition, the record that calls typically the span method of typically the RandomAccessFile object may in addition throw an IOException. You thus specify this carries out offer in the announcement for the getFileLength technique to trap IOException.

Leave a Reply

Your email address will not be published. Required fields are marked *