http://www.technicalpage.net/search/label/SQL

>> throwing Exception

Exception Handling in Java/Selenium Part 2:

throws Exception


Exception can be handled using try/catch blocks ( discussed in previous tutorial, click here ) or by throwing exception which is used in method definition. In this tutorial, we discuss about throwing exception.

Syntax:
public void methodName() throws Exception_type(or Exception_types separated by ",") {
executable code ;
}

Exception Types could be any from below list( below list has most common exception types) . You can use the Exception type based on the nature of your code ie what it is going to execute and what kind of exception might occur . You may use any one of the exceptions or combination of more than one exceptions , depending upon your code and how you want to handle if the exception occurs.

Most common Exceptions:
ArithmeticException
NullPointerException
ArrayIndexBoundException
IOException
FileNotFoundException
Exception

For example:
Let's write a code to open a txt file as below:

public static void main(java.lang.String[] args) throws IOException {
             
              File fl = new File("C:\\folder1\\folder2\\fileName.txt");                                 Desktop desktop = Desktop.getDesktop();
             desktop.open(fl);
}

OR

public static void main(java.lang.String[] args) throws IOException, Exception {
             
              File fl = new File("C:\\folder1\\folder2\\fileName.txt");                                 Desktop desktop = Desktop.getDesktop();
             desktop.open(fl);
}

OR

public static void main(java.lang.String[] args) throws Exception {
//Exception is higher level exception which handles IOException as well.         
              File fl = new File("C:\\folder1\\folder2\\fileName.txt");                                 Desktop desktop = Desktop.getDesktop();
             desktop.open(fl);
}

No comments:

Post a Comment