> exceptions in java ~ Online tutorial

exceptions in java

Exceptions
  • Programmers in any language endeavor to write bug-free programs, programs that never
    crash, programs that can handle any circumstance with grace and recover from unusual
    situations without causing a user any undue stress. Good intentions aside, programs like
    this don’t exist.
  • In real programs, errors occur because programmers didn’t anticipate possible problems,
    didn’t test enough, or encountered situations out of their control—bad data from users,
    corrupt files that don’t have the correct data in them, network connections that don’t connect,
    hardware devices that don’t respond, sun spots, gremlins, and so on.
  • In Java, the strange events that might cause a program to fail are called exceptions. Java defines a number of language features that deal with exceptions:
  • How to handle exceptions in your code and recover gracefully from potential
    problems
  • How to tell Java and users of your classes that you’re expecting a potential
    exception
  • How to create an exception if you detect one
  • How your code is limited, yet made more robust by exceptions
    With most programming languages, handling error conditions requires much more work
    than handling a program that is running properly.
Here’s the structure of one possible solution:

int status = loadTextFile();
if (status != 1) {
// something unusual happened, describe it
switch (status) {
case 2:
System.out.println(“File not found”);
break;
case 3:
System.out.println(“Disk error”);
break;
case 4:
System.out.println(“File corrupted”);
break;
default:
System.out.println(“Error”);
}
} else {
// file loaded OK, continue with program
}


This code tries to load a file with a method call to loadTextFile(), which presumably
has been defined elsewhere in the class. The method returns an integer that indicates
whether the file loaded properly (a value of 1) or an error occurred (anything other
than 1).

Buy It Now




Please Give Us Your 1 Minute In Sharing This Post!
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Powered By: BloggerYard.Com

0 comments: