1. Exception
Exception are a mechanism used by many programming language to describe what to do when something unexpected happens. Typically, something unexpected is an error of some sort, for example when a method is invoked with unacceptable arguments, or a network connections fails, or the user ask to open a non-existed file. The java programming language provides two broad categories of exceptions, known as checked and unchecked exceptions 1. Checked Exception are those that programmer is expected to handle in the program. Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at Compile time.
In this example we are reading the file myfile.txt and displaying its content on the screen. In this program there are three places where an checked exception is thrown as mentioned in the comments below. FileInputStream which is used for specifying the file path and name, throws FileNotFoundException. The read() method which reads the file content throws IOException and the close() method which closes the file input stream also throws IOException. import java.io.*; class Example { public static void main(String args[]) { FileInputStream fis = null; /*This constructor FileInputStream(File filename) * throws FileNotFoundException which is a checked * exception*/ fis = new FileInputStream("B:/myfile.txt"); int k;
/*Method read() of FileInputStream class also throws * a checked exception: IOException*/ while(( k = fis.read() ) != -1) { System.out.print((char)k); }
/*The method close() closes the file input stream * It throws IOException*/ fis.close(); } } Output: Exception in thread "main" java.lang.Error: Unresolved compilation problems: Unhandled exception type FileNotFoundException Unhandled exception type IOException Unhandled exception type IOException
المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .
|