0
Can we use 'if' condition to handle exception in Java?If so then what is the use of try/catch stuff?
2 odpowiedzi
+ 3
if and else are for things we expect to happen (for example different choices the user makes).
try, throw and catch are for things that shouldn't happen but do anyway (like when a file that's supposed to be loaded is damaged and can't be loaded).
+ 2
sometimes we want to handle an error from another class, this is where we usually use throw, throws, try-catch.
public class Program
{
public static void main(String[] args) {
try{
Box b = new Box(-4);
}catch(Exception e){
System.out.println("Error: "+e.getMessage());
}
}
}
class Box{
private int volume;
public Box(int v) throws Exception {
if(v < 1) throw new Exception("Box Volume cant be 0 or negative");
volume = v;
}
}