In Java methods can use the keyword throws Exception and all errors are thrown when you call the method, this reduce the uses of try catch
I'm learning JavaScript now, but I find hard to believe that there's no similar keyword in JavaScript, are we suppose to surround everything with try-catch blocks?
I find myself checking every variable like this
if(packet.username && packet.password && packet.id && packet.errors)
followed by checking the type of all this vars
and using a lot of try catch blocks which make the code very large and unclear
I find it annoying really, is there a way to handle any errors and catching them in the main function call?
Edit: since it been 3 answers and all of them are misunderstanding the question, sorry about that, English isn't my first language
I don't want to know how to throw an exception, take this java vs javascript example
I'm programming a server which should handle all kinds of errors, now if an error occurs is most certainly a client is sending its own custom data that server don't expect....
In java, I would do something like this
try{
// I only need to try catch here....
parsePacket();
}
catch(Exception e){
e.print();
}
void parsePacket() throws Exception{
//.....
// a lot of more possible errors here mainly the ones the server doesn't expect....
//.....
anotherFunction();
//imagine a lot of more functions here that can throw an error
}
void anotherFunction() throws Exception{
//.....
// a lot of more posible errors here....
//.....
}
How pretty? just one try-catch block, however in javascript I find myself doing this
JavaScript
try{
parsePacket();
}
catch(Exception e){
e.print();
}
void parsePacket(){
try{
//for some reason I have to catch TypeErrors and other ones here too
//.....
// a lot of more posible errors
//.....
anotherfunction(()=>{
try{
//.....
// a lot of more posible errors here
//.....
}
catch(err){
}
})
}
catch(err){
}
}
void anotherFunction(){
try{
//.....
// a lot of more posible errors here
//.....
}
catch(err){
}
}
And it can get ugly pretty fast