14.3 C
London
Thursday, September 12, 2024

Exception dealing with in Java: The fundamentals



The FileInputStream(String filename) constructor creates an enter stream to the file recognized by filename. This constructor throws FileNotFoundException when the file doesn’t exist, refers to a listing, or one other associated drawback happens. The FileOutputStream(String filename) constructor creates an output stream to the file recognized by filename. It throws FileNotFoundException when the file exists however refers to a listing, doesn’t exist and can’t be created, or one other associated drawback happens.

FileInputStream gives an int learn() methodology to learn one byte and return it as a 32-bit integer. This methodology returns -1 on end-of-file. FileOutputStream gives a void write(int b) methodology to put in writing the byte within the decrease 8 bits of b. Both methodology throws IOException when one thing goes fallacious.

The majority of the instance is a whereas loop that repeatedly learn()s the following byte from the enter stream and write()s that byte to the output stream, till learn() alerts end-of-file.

The attempt block’s file-copy logic is simple to comply with as a result of this logic isn’t mixed with exception-checking code (if assessments and associated throw statements hidden within the constructors and strategies), exception-handling code (which is executed in a number of related catch blocks), and cleanup code (for closing the supply and vacation spot recordsdata; this code is relegated to an related lastly block). In distinction, C’s lack of an analogous exception-oriented framework leads to extra verbose code, as illustrated by the next excerpt from a bigger C cp utility (on this article’s code archive) that copies a supply file to a vacation spot file:

if ((fpsrc = fopen(argv[1], "rb")) == NULL)
{
   fprintf(stderr, "unable to open %s for readingn", argv[1]);
   return;
}

if ((fpdst = fopen(argv[2], "wb")) == NULL)
{
   fprintf(stderr, "unable to open %s for writingn", argv[1]);
   fclose(fpsrc);
   return;
}

whereas ((c = fgetc(fpsrc)) != EOF)
   if (fputc(c, fpdst) == EOF)
   {
      fprintf(stderr, "unable to put in writing to %sn", argv[1]);
      break;
   }

On this instance, the file-copy logic is more durable to comply with as a result of the logic is intermixed with exception-checking, exception-handling, and cleanup code:

  • The 2 == NULL and one == EOF checks are the equal of the hidden throw statements and associated checks.
  • The three fprintf() perform calls are the exception-handling code whose Java equal can be executed in a number of catch blocks.
  • The fclose(fpsrc); perform name is cleanup code whose Java equal can be executed in a lastly block.

Utilizing catch blocks to catch exceptions

Java’s exception-handling functionality is predicated on catch blocks. This part introduces catch and numerous catch blocks.

The catch block

Java gives the catch block to delimit a sequence of statements that deal with an exception. A catch block has the next syntax:

catch (throwableType throwableObject)
{
   // a number of statements that deal with an exception
}

The catch block is just like a constructor in that it has a parameter listing. Nonetheless, this listing consists of just one parameter, which is a throwable sort (Throwable or considered one of its subclasses) adopted by an identifier for an object of that sort.

When an exception happens, a throwable is created and thrown to the JVM, which searches for the closest catch block whose parameter sort instantly matches or is the supertype of the thrown throwable object. When it finds this block, the JVM passes the throwable to the parameter and executes the catch block’s statements, which might interrogate the handed throwable and in any other case deal with the exception. Take into account the next instance:

catch (FileNotFoundException fnfe)
{
   System.err.println(fnfe.getMessage());
}

This instance (which extends the earlier attempt block instance) describes a catch block that catches and handles throwables of sort FileNotFoundException. Solely throwables matching this kind or a subtype are caught by this block.

Suppose the FileInputStream(String filename) constructor throws FileNotFoundException. The JVM checks the catch block following attempt to see if its parameter sort matches the throwable sort. Detecting a match, the JVM passes the throwable’s reference to fnfe and transfers execution to the block. The block responds by invoking getMessage() to retrieve the exception’s message, which it then outputs.

Specifying a number of catch blocks

You possibly can specify a number of catch blocks after a attempt block. For instance, think about this bigger excerpt from the aforementioned Copy utility:

FileInputStream fis = null;
FileOutputStream fos = null;
{
   fis = new FileInputStream(args[0]);
   fos = new FileOutputStream(args[1]);
   int c;
   whereas ((c = fis.learn()) != -1)
      fos.write(c);
}
catch (FileNotFoundException fnfe)
{
   System.err.println(fnfe.getMessage());
}
catch (IOException ioe)
{
   System.err.println("I/O error: " + ioe.getMessage());
}

The primary catch block handles FileNotFoundExceptions thrown from both constructor. The second catch block handles IOExceptions thrown from the learn() and write() strategies.

When specifying a number of catch blocks, don’t specify a catch block with a supertype earlier than a catch block with a subtype. For instance, don’t place catch (IOException ioe) earlier than catch (FileNotFoundException fnfe). In the event you do, the compiler will report an error as a result of catch
(IOException ioe)
would additionally deal with FileNotFoundExceptions, and catch (FileNotFoundException
fnfe)
would by no means have an opportunity to execute.

Likewide, don’t specify a number of catch blocks with the identical throwable sort. For instance, don’t specify two catch (IOException ioe) {} blocks. In any other case, the compiler experiences an error.

Utilizing lastly blocks to wash up exceptions

Whether or not or not an exception is dealt with, it’s possible you’ll have to carry out cleanup duties, corresponding to closing an open file. Java gives the lastly block for this function.

The lastly block consists of key phrase lastly adopted by a brace-delimited sequence of statements to execute. It could seem after the ultimate catch block or after the attempt block.

Cleansing up in a try-catch-finally context

When sources have to be cleaned up and an exception isn’t being thrown out of a technique, a lastly block is positioned after the ultimate catch block. That is demonstrated by the next Copy excerpt:

FileInputStream fis = null;
FileOutputStream fos = null;
attempt
{
   fis = new FileInputStream(args[0]);
   fos = new FileOutputStream(args[1]);
   int c;
   whereas ((c = fis.learn()) != -1)
      fos.write(c);
}
catch (FileNotFoundException fnfe)
{
   System.err.println(fnfe.getMessage());
}
catch (IOException ioe)
{
   System.err.println("I/O error: " + ioe.getMessage());
}
lastly
{
   if (fis != null)
      attempt
      {
         fis.shut();
      }
      catch (IOException ioe)
      {
         // ignore exception
      }

   if (fos != null)
      attempt
      {
         fos.shut();
      }
      catch (IOException ioe)
      {
         // ignore exception
      }
}

If the attempt block executes with out an exception, execution passes to the lastly block to shut the file enter/output streams. If an exception is thrown, the lastly block executes after the suitable catch block.

FileInputStream and FileOutputStream inherit a void shut() methodology that throws IOException when the stream can’t be closed. Because of this, I’ve wrapped every of fis.shut(); and fos.shut(); in a attempt block. I’ve left the related catch block empty for example the frequent mistake of ignoring an exception.

An empty catch block that’s invoked with the suitable throwable has no method to report the exception. You would possibly waste plenty of time monitoring down the exception’s trigger, solely to find that you could possibly have detected it sooner if the empty catch block had reported the exception, even when solely in a log.

Cleansing up in a try-finally context

When sources have to be cleaned up and an exception is being thrown out of a technique, a lastly block is positioned after the attempt block: there are not any catch blocks. Take into account the next excerpt from a second model of the Copy utility:

public static void principal(String[] args)
{
   if (args.size != 2)
   {
      System.err.println("utilization: java Copy srcfile dstfile");
      return;
   }

   attempt
   {
      copy(args[0], args[1]);
   }
   catch (IOException ioe)
   {
      System.err.println("I/O error: " + ioe.getMessage());
   }
}

static void copy(String srcFile, String dstFile) throws IOException
{
   FileInputStream fis = null;
   FileOutputStream fos = null;
   attempt
   {
      fis = new FileInputStream(srcFile);
      fos = new FileOutputStream(dstFile);
      int c;
      whereas ((c = fis.learn()) != -1)
         fos.write(c);
   }
   lastly
   {
      if (fis != null)
         attempt
         {
            fis.shut();
         }
         catch (IOException ioe)
         {
            System.err.println(ioe.getMessage());
         }

      if (fos != null)
         attempt
         {
            fos.shut();
         }
         catch (IOException ioe)
         {
            System.err.println(ioe.getMessage());
         }
   }
}

The file-copying logic has been moved right into a copy() methodology. This methodology is designed to report an exception to the caller, however it first closes every open file.

This methodology’s throws clause solely lists IOException. It isn’t essential to incorporate FileNotFoundException as a result of FileNotFoundException subclasses IOException.

As soon as once more, the lastly clause presents plenty of code simply to shut two recordsdata. Within the second a part of this collection, you’ll be taught concerning the try-with-resources assertion, which obviates the necessity to explicitly shut these recordsdata.

In conclusion

This text launched you to the fundamentals of Java’s conventional exception-oriented framework, however there may be way more to know. The second half of this tutorial introduces Java’s extra superior exception-oriented language options and library varieties, together with try-with-resources.

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here