Exceptions

 An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.

package com.main;

public class Main {
public static void main(String[] args) {

try {
int a = 5;
int b = 0;
int k = a / b;
System.out.println("output is :" + k);
}catch (Exception ex){
System.err.println("Error ");
}

System.out.println("continue...");
}
}
Output:
Error
continue...
If an error(exception) occurs java skips the rest of the code and jumps 
directly to the catch block and then the rest of the code arter catch block.

package com.main;

public class Main {
public static void main(String[] args) {

try {
int a = 5;
int b = 0;
int k = a / b;
System.out.println("output is :" + k);
}catch (Exception ex){
try {
int a = 5;
int b = 0;
int k = a / b;
System.out.println("output is :" + k);
}catch (Exception ee){
System.out.println("We tried 2 times...");
}
}

System.out.println("continue...");
}
}

Output:
We tried 2 times...
continue...

Multiple catch:
package com.main;

public class Main {
public static void main(String[] args) {

try {
int a = 5;
int b = 0;
int k = a / b;
System.out.println("output is :" + k);
} catch (IllegalArgumentException | ArrayIndexOutOfBoundsException | ArithmeticException ex) {
System.err.println("Error ");
} catch (Exception ex){
ex.printStackTrace();
}
System.out.println("continue...");
}
}

*How to create out own Exception class?
package com.main;

public class MyException extends Exception{

public MyException(){
super("Access is Denied!!!");
}
}
package com.main;

public class Main {
public static void main(String[] args) {

int age = 17;
try {
if (age < 18) throw new MyException();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Output:
com.main.MyException: Access Denied!!!
	at com.main.Main.main(Main.java:10)

In Java, there are two types of exceptions:

1) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Exceptions that extedns from Exception class are Checked Exceptions.

2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions.

Exceptions that extedns from RuntimeException class are Unchecked Exceptions.




Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

SE_21_Lesson_9: Initialization Blocks, Wrapper types, String class