Throwing exceptions:
When we detect a problem, we can create an exception object by using the keyword throw. By way of example, we look in a little more detail at the checkFormat method introduced earlier. Suppose we expect the file we are checking to be structured into a header section of a certain fixed length (defined by the constant value HEADER_LENGTH), followed by various other sections. If we unexpectedly come to the end of the file before the number of characters expected in the header has been read, we can throw an exception. In this case, an appropriate choice would be an exception of the class EOFException.
public boolean checkFormat (String fileName)
throws EOFException
{
// part of code for method checkFormat
...
int charsInHeader;
charsInHeader = readHeader(file, header);
if (charsInHeader < HEADER_LENGTH)
{
throw new EOFException();
}
...
}
Note the use of the new operator and empty brackets after EOFException in the throw statement. This indicates that we are using a constructor for the EOFException class: in particular, the constructor that has no arguments.
Exceptions within the Java class library can be created using a zero-argument constructor, like this, or using a one-argument constructor. The one-argument constructor allows us to add a string to indicate some more detail about what has happened to cause the exception. In the example above, if we wanted to pass more information back to the code that calls the checkFormat method, we could write the throw statement like this:
throw new EOFException
("EOF error at file position " + charsInHeader);
This associates a string with the exception object, giving more details about the circumstances of the error. In this case, the string consists of some informative text together with the value of the variable charsInHeader, which indicates how far through the file the error occurred.
Java Assignment Help - Java Homework Help
Struggling with java programming language? Are you not finding solution for your Throwing exceptions homework and assignments? Live Throwing exceptions experts are working for students by solving their doubts & questions during their course studies and training program. We at Expertsmind.com offer Throwing exceptions homework help, java assignment help and Throwing exceptions projects help anytime from anywhere for 24x7 hours. Computer science programming assignments help making life easy for students.
Why Expertsmind for assignment help
- Higher degree holder and experienced experts network
- Punctuality and responsibility of work
- Quality solution with 100% plagiarism free answers
- Time on Delivery
- Privacy of information and details
- Excellence in solving java programming language queries in excels and word format.
- Best tutoring assistance 24x7 hours