1public static void foo() throws IOException {
2 // some code here, when something goes wrong, you might do:
3 throw new IOException("error message");
4}
5
6public static void main(String[] args) {
7 try {
8 foo();
9 } catch (IOException e) {
10 System.out.println(e.getMessage());
11 }
12}
1public static void main(String[] args) {
2 Scanner kb = new Scanner(System.in);
3 System.out.println("Enter a number");
4 try {
5 double nb1 = kb.nextDouble();
6 if(nb1<0)
7 throw new ArithmeticException();
8 else System.out.println( "result : " + Math.sqrt(nb1) );
9 } catch (ArithmeticException e) {
10 System.out.println("You tried an impossible sqrt");
11 }
12}
1In java exception is an object. Exceptions are created when an abnormal
2situations are arised in our program. Exceptions can be created by JVM or
3by our application code. All Exception classes are defined in java.lang.
4In otherwords we can say Exception as run time error.
5
1An exception is an event, which occurs during the execution of a
2program, that disrupts the normal flow of the program's instructions.
11.Unchecked: occurs during run time
22.Checked Exceptions:occurs during the compile time.
3needs to be handled IMMEDIATELY
4Exception handling: try & catch: blocks, used for handling the exception
5
6throws keyword is used within the method signature
7disadvantage is: throws keyword whoever calls the method
8will have to handle the exception again but with
9try/catch you handle once. Try/catch is better way to handle it
10in utility class. Next time you call method you don’t get any exceptions
11
12most common Exception like NullPointerExceptio,
13ArrayIndexOutOfBound, ClassNotFoundException, IOException.
14are unchecked and they are descended from java.lang.RuntimeException
15In Selenium: nosuchelement, nostaleexception, nosuchaframe
16In SQL: SQL exception